开发者

Convert n-byte int to bytes in python3

开发者 https://www.devze.com 2023-02-05 14:37 出处:网络
I want to convert an 32-byte (although I might need other lengths) integer to a 开发者_如何学Cbytes object in python. Is there a clean and simple way to do this?to_bytes(length, byteorder[, signed]) i

I want to convert an 32-byte (although I might need other lengths) integer to a 开发者_如何学Cbytes object in python. Is there a clean and simple way to do this?


to_bytes(length, byteorder[, signed]) is all you need starting from 3.2. In this case, someidentifier.to_bytes(4,'big') should give you the bytes string you need.


I'm guessing you need a 32-bit integer, and big-endian to boot:

>>> from ctypes import c_uint32
>>> l = c_uint32(0x12345678)
>>> bytes(l)
b'xV4\x12'

There is c_uint8, c_uint16 and c_uint64 as well. For longer ints you need to make it manually, using divmod(x, 256).

>>> def bytify(v):
...   v, r = divmod(v, 256)
...   yield r
...   if v == 0:
...      raise StopIteration
...   for r in bytify(v):
...     yield r
... 
>>> [x for x in bytify(0x12345678)]
[120, 86, 52, 18]
>>> bytes(bytify(0x12345678))
b'xV4\x12
>>> bytes(bytify(0x123456789098765432101234567890987654321))
b'!Ce\x87\t\x89gE#\x01!Ce\x87\t\x89gE#\x01'


You can use bytes("iterable") directly. Where every value in iterable will be specific byte in bytes(). Example for little endian encoding:

>>> var=0x12345678
>>> var_tuple=((var)&0xff, (var>>8)&0xff, (var>>16)&0xff, (var>>24)&0xff)
>>> bytes(var_tuple)
b'xV4\x12'


Suppose you have

var = 'і' # var is ukrainian і

We want to get binary from it. Flow is this. value/which is string => bytes => int => binary

binary_var = '{:b}'.format(int.from_bytes(var.encode('utf-8'), byteorder='big'))

Now binary_var is '1101000110010110'. It type is string.

Now go back, you want get unicode value from binary:

int_var = int(binary_var, 2) # here we get int value, int_var = 53654

Now we need convert integer to bytes. Ukrainian 'і' is not gonna fit into 1 byte but in 2. We convert to actual bytes bytes_var = b'\xd1\x96'

bytes_var = int_var.to_bytes(2, byteorder='big') 

Finally we decode our bytes.

ukr_i = bytes_var.decode('utf-8') # urk_i = 'і'
0

精彩评论

暂无评论...
验证码 换一张
取 消