Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - pack exactly 24 bits into unsigned/signed int

Tags:

python

I need to send exactly 24 bits over an ethernet connection, and the program on the other end expects an unsigned int in some cases and a signed int in others (C types). I want to use the struct class, but it doesn't have a type with 3 bytes built in (like uint24_t).

Similar questions to this have been asked, but the answer always involves sending 4 bytes and padding the data packet with zeros. I cannot do this, however, since I am not writing the program which is receiving the data, and it expects exactly 24 bits.

I am very new at this type of programming, so help is appreciated!

like image 910
gauss_fan Avatar asked Nov 14 '25 10:11

gauss_fan


1 Answers

Using the struct module, create a string that contains exactly three 8-bit bytes.

import struct
# 24 bits: 01010101 10101010 11110000
byte1 = 0x55
byte2 = 0xaa
byte3 = 0xf0
data = struct.pack("BBB", byte1, byte2, byte3)

Depending on how you get the bits to send, you can define the string directly:

data = '\x55\xaa\xf0'
like image 71
chepner Avatar answered Nov 17 '25 07:11

chepner