0

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

2
  • It's depend how you want to code your bytes (little endian or big). You want the string representation or the bytes representation ? Commented Jun 3, 2014 at 19:53
  • Note that bytes is just another name for the str type, and str([1024]) just produces a string representing the list: '[1024]'. Commented Jun 3, 2014 at 20:09

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You certainly did the better job decrypting this question. :)
Thanks chepner. Since my data is supposed to be 64 bits is there a way to unpack it without specifying 8 Bs (for cleaniliness reasons)? i.e. struct.unpack("BBBBBBBB", struct.pack("<L", 1024))
struct.unpack("8B", struct.pack("<L", 1024)) will unpack into an 8 byte array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.