I want to convert an 32-byte (although I might need other lengths) integer to a bytes object in python. Is there a clean and simple way to do this?
-
What format has your integer currently?Sven Marnach– Sven Marnach2011年01月18日 21:18:25 +00:00Commented Jan 18, 2011 at 21:18
-
532-byte integer? That's a lot of nu... bytes. What exactly are you trying to achieve, and what did you already try?Cat Plus Plus– Cat Plus Plus2011年01月18日 21:18:53 +00:00Commented Jan 18, 2011 at 21:18
-
I have sha hashes in 0x... form, python is perfectly happy converting them to integers, but how do I get from there to bytes?Peter– Peter2011年01月18日 21:37:55 +00:00Commented Jan 18, 2011 at 21:37
4 Answers 4
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.
4 Comments
to_bytes is in bytes, not bits, so it should be 4 instead of 32.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'
5 Comments
bytes can be initialised with an array of ints in the range (0, 256).reverse() of course.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'
Comments
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 = 'і'