I want to pack a 10-bit integer and a 54-bit integer into a 64-bit structure. But this code ends up using 128 bits.
from ctypes import *
class ABC(Structure):
_fields_ = [("a", c_int, 10), ("b", c_uint64, 54)]
print(sizeof(ABC) * 8) # 128
I want to pack a 10-bit integer and a 54-bit integer into a 64-bit structure. But this code ends up using 128 bits.
from ctypes import *
class ABC(Structure):
_fields_ = [("a", c_int, 10), ("b", c_uint64, 54)]
print(sizeof(ABC) * 8) # 128
For whatever reason, ctypes
doesn't do bit packing properly when you mix different width objects into the same byte. Something like this appears to work for me:
class ABC(Structure):
_pack_ = 1
_fields_ = [("a",c_int64,10),("b",c_uint64,54)]
Considering int_10
and int_54
are integers with desired bitness:
>>> def pack(int_10, int_54):
... return (int_10 & 0x3FF) | (int_54 & 0x3FFFFFFFFFFFFF) << 10
>>> bin(pack(1, 1))
'0b10000000001'
>>> bin(pack(1, 2 ** 54 - 1))
'0b1111111111111111111111111111111111111111111111111111110000000001'
>>> bin(pack(2 ** 10, 2 ** 54))
'0b0'
You can then pack the resulting integer using struct.pack
to get a byte string.
>>> import struct
>>> struct.pack('Q', pack(2 ** 10 - 1, 2 ** 54 - 1))
'\xff\xff\xff\xff\xff\xff\xff\xff'