How to store the int of specific bits(24bits, 16bits, etc) in Python?
When I do the compress the data with compact code, I don't know how to deal with the integer, I need to store an integer into 1bytes, 2bytes, 3bytes, etc, memory, How can I do this in Python.
Or, how to change the 开发者_StackOverflow社区tuple (1, 0, 1, ..., 1) (24bits) into exact 3bytes storage
The struct
module in the standard library packs data into bytes.
If you need to pack in arbitrary numbers of bytes then it might be better to use a bytearray
than rely on the struct
module, for example:
>>> a = bytearray(3) # create 3 byte array
>>> a[0] = 0x3e
>>> a[1] = 0xff
>>> a[2] = 0x00
Note that the memory overhead of any Python object is going to be considerably more than a few bytes, so if you are really worried about memory use then you should store all your data together in as few objects as possible.
Depending on your exact needs a third party module such as bitstring could be helpful (full disclosure: I wrote it).
>>> b = bitstring.BitArray((1,0,1,1,1,0,0,1,1,1,0,1,0,1,1,1))
>>> b.bytes
'\xb9\xd7'
>>> b.uint
47575
精彩评论