Reading least significant bits in Python

2019-02-26 11:55发布

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 substracting.

(I am a sys admin by trade so, I don't know many of the basics- please bare with me!)

4条回答
▲ chillily
2楼-- · 2019-02-26 12:01

Just apply a bit mask:

sev = int(pri) & 0x07

(0x07 is 00000111)

查看更多
放荡不羁爱自由
3楼-- · 2019-02-26 12:07
SEV = PRI & 7
FAC = PRI >> 3

Like that.

查看更多
Root(大扎)
4楼-- · 2019-02-26 12:08

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

查看更多
一夜七次
5楼-- · 2019-02-26 12:20

Try the following

result = FAC & 0x7
查看更多
登录 后发表回答