How to unpack 4 bytes of binary data as 3-byte and 1 byte values?

I have 4 bytes of binary data (big-endian) that I want to unpack. If it contained two two-byte unsigned values, it would be simple:

a, b = data.unpack("C>C>")

But what if the data contains a 3-byte value ( a) followed by a 1-byte value ( b)? The decompression method does not seem to be able to handle formats other than 8-, 16-, 32- and 64-bit integers. Here is what I came up with:

a, b = data.unpack("L>XC")   # "L>": unpack a 32-bit unsigned int (big-endian)
                             # "X":  rewind (skip back) one byte
                             # "C":  unpack an 8-bit unsigned int
a >>= 8                      # drop the last (lowest) byte from a

(If the data were of little value, a &= 0xFFFFFFit could be used to delete the last (highest) byte.)

Is there a more elegant way to unzip these values?

+4
2

. ( )

a, b, c = data.unpack("S>CC") # C doesn't have endianness
ab = a << 8 + b

, .

- 32- int -.

ab, = data.unpack("L>")
a, b = ab >> 8, ab & 0xFF
+4

@hobbs . , Numeric#divmod :

ab, = data.unpack('L>')
a, b = ab.divmod(2**8)

:

a, b = data.unpack('L>')[0].divmod(2**8)
+2

Source: https://habr.com/ru/post/1628231/


All Articles