Reading least significant bits in Python

家住魔仙堡 提交于 2019-12-02 00:28:08

问题


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.


回答1:


SEV = PRI & 7
FAC = PRI >> 3

Like that.




回答2:


Just apply a bit mask:

sev = int(pri) & 0x07

(0x07 is 00000111)




回答3:


Try the following

result = FAC & 0x7



回答4:


The normal way to extract the least significant bits would be to do a bitwise AND with the appropriate mask (7 in this case)



来源:https://stackoverflow.com/questions/4822130/reading-least-significant-bits-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!