binary - Using Python to manipulate 31-bits -


i have specification outlines how instructions should sent on serial.

currently crafting packets go on connection.

one segment of packet, requires 32-bit (4 byte) binary number. first 31-bits 'data' , last bit merely flag.

so, max decimal number fit in data is: 2147483647 (2^31). data never bigger this, cool!

my problem, how go encoding data 31-bits binary, setting final bit enable flag?

say data 7aaaaaaa desirable way of converting 31 bit binary adding 1 or 0 end?

edit - i'm using python 3.4

i think can use binary shift add flag number:

a = 0x7aaaaaaa                # 2058005162 = 0b1111010101010101010101010101010 f = 1                         # 1 = 0b1  packet = + (f << 31)        # + 0b10000000000000000000000000000000 bin(packet)                   # 0b11111010101010101010101010101010 

to unpack can use mask , binary , this:

mask = (1 << 31) - 1          # 2147483647 = 0b1111111111111111111111111111111 = packet & mask             # 2058005162 = 0b1111010101010101010101010101010 f = packet >> 31              # 1 = 0b1 

Comments