Reputation: 3941
I am new to python so please bear with if it sounds a novice question. I looked it up but different sources tell me different things so I decided to ask it here. And doc is not very clear.
I have an int that I want to convert to bytes.
#1024 should give me 0000010000000000
print bytes([1024])
[1024]
If I use bytes() I assume I get a list since when I print I end up getting [1024]. However if I do
print bytes([1024])[0]
[
I get [ back. Why is this? So it does not return a list?
Is there a way to get the byte streams back given an integer? Ideally I want something as follows:
x = tobyte(1024)
print x[0] #should give me 0 00000000
print x[1] #should give me 8 00000100
I need to be able to use x[0] elsewhere in the code i.e. to be passed to base64 encode where I expect my data to be 64 bits
Upvotes: 0
Views: 236
Reputation: 531265
To get the individual bytes from an integer, use struct
:
individual_bytes = struct.unpack("BB", struct.pack("<H", 1024))
First, "<I"
packs the integer as a 16-bit value, using little-endian ordering. Then "BB"
unpacks the byte string into two separate 8-bit values.
Upvotes: 2