读取Python中的最低有效位
我必须在 Python 中解析系统日志消息的功能和严重性。这些值作为单个整数随每条消息一起提供。事件的严重性为 0-7,在整数的 3 个最低有效位中指定。从数字中评估这 3 位的最简单/最快的方法是什么?
我现在的代码只是右移 3 位,然后将该数字乘以 8,然后从原始值中减去结果。
FAC = (int(PRI) >> 3)
SEV = PRI - (FAC * 8)
必须有一种不太复杂的方法来做到这一点,而不是擦除这些位并进行减法。
I am having to parse the Facility and Severity of syslog messages in Python. These values come with each message as a single integer. The severity of the event is 0-7, specified in the 3 least significant bits in the integer. What is the easiest/fastest way to evaluate these 3 bits from the number?
The code I have right now just does a 3 bit right shift, than multiplies that number times 8, and subtracts the result from the original.
FAC = (int(PRI) >> 3)
SEV = PRI - (FAC * 8)
There must be a less convoluted way to do this- rather than wiping out the bits, and subtracting.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
就这样。
Like that.
只需应用位掩码:
(0x07 是 00000111)
Just apply a bit mask:
(0x07 is 00000111)
尝试以下操作
Try the following
提取最低有效位的正常方法是使用适当的掩码(本例中为 7)进行按位 AND 运算
The normal way to extract the least significant bits would be to do a bitwise AND with the appropriate mask (7 in this case)