gauss_fan
gauss_fan

Reputation: 33

python - pack exactly 24 bits into unsigned/signed int

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!

Upvotes: 3

Views: 1815

Answers (1)

chepner
chepner

Reputation: 532093

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'

Upvotes: 4

Related Questions