Reputation: 487
I'm trying to send byte message via TCP socket. I have one static byte that is hex word 0xaa
. On static byte I need to concatenate dynamic byte which MSB is always 0 then I have bits from 6-4 which are variable (from 000 to 100) and than bits from 3-0 are also variable (from 0000 - 1000). What is the best way to do this? I've seen that I can use bitarray
and BitArray
class from bitstring
but I would like to know what is the best solution for this problem. Also I'm need to know how to convert bitarray back to bytes so I can send it via TCP.
Example of what I need:
leading_byte = 0xaa
bit7 = 0 (bit)
options = { 'a' : 000 (bits), 'b' : 001 ...}
versions = { 'i' : 0000 (bits), 'i' : 0001 ...}
bits6_4 = options['a']
bits3_0 = versions['i']
byte_message = leading_byte + bit7 + bit6_4 + bits3_0
socket.send(byte_message)
Upvotes: 1
Views: 134
Reputation: 42758
Use bit shifting and ordinary chr
:
byte_message = chr(0xaa) + chr((bits6_4 << 4) | bits3_0)
Upvotes: 2