Home > Back-end >  Python - Pack 4 int into 4 bytes
Python - Pack 4 int into 4 bytes

Time:05-29

I would like pack my color values in 4 bytes.

For example: having (255,254,253,252) I would like have back b'\xff\xfe\xfd\xfc'

Instead

r = 255
g = 254
b = 253
a = 252

tot = a << 3 | b << 2 | g << 1 | r

tot_byte = struct.pack('i', tot)

returns: b'\xff\x07\x00\x00'

if I do:

tot = a << 24 | b << 16 | g << 8 | r

tot_byte = struct.pack('i', tot)

I got back "argument out of range".

What I should do?

CodePudding user response:

Change this:

tot_byte = struct.pack('i', tot)

To this:

tot_byte = struct.pack('I', tot)

See here for the list of available formats.

CodePudding user response:

Pack format i is for a signed integer, with the range [-2147483648, 2147483647]. The value of tot lies outside this range.

You need to use I, the unsigned equivalent. For extra portability, add a leading < sign to force standard sizes and little-endianness, i.e.:

tot = a << 24 | b << 16 | g << 8 | r
tot_byte = struct.pack('<I', tot)

Reference: https://docs.python.org/3/library/struct.html#format-characters

  • Related