How to convert an integer to a binary string in Python 3?

Asked

Viewed 198 times

1

If I want to convert between integers and characters, use chr and ord:

>>> chr(10)
'\n'
>>> ord('$')
36

However I need to do a string test binary, something new in Python 3, and I - who only have experience with Python 2 - have no idea how to do it:

# O que eu sei
teste(b'\x00')
teste(b'\x01')
teste(b'\x02')
...
teste(b'\xff')

# O que eu quero
for i in range(256)
    teste(???)
  • I think you are looking for this: http://pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/

  • @Andrera This article only talks about the conversion between strings (text) and bytes through a encoding. The problem is those byte sequences that do not represent any text in whichever encoding (ex.: b"\xdb" is not a valid string in any Unicode encoding). Anyway, I want to work with "raw" bytes, not text, any such conversion would be a "gambiarra".

1 answer

1


No Stack Overflow in English has an answer.

Then your loop would be (I limited the maximum but test it works):

>>> for i in range(20):
...   print(bytes([i]))
... 
b'\x00'
b'\x01'
b'\x02'
b'\x03'
b'\x04'
b'\x05'
b'\x06'
b'\x07'
b'\x08'
b'\t'
b'\n'
b'\x0b'
b'\x0c'
b'\r'
b'\x0e'
b'\x0f'
b'\x10'
b'\x11'
b'\x12'
b'\x13'

Don’t worry about the b'\t', because they are well known special characters.

  • Great, thanks! I had a quick look at documentation of bytes, but without an example I didn’t realize I could use it that way (with a iterable whole).

  • Hi, Paul, temporary comment and off-topic. It appeared to me the following edition of its to approve and decided to jump because it’s not my thing. With luck, the reviewers who decide know Mongodb, but they may reject it; it would be the natural reaction within this eco-system. What I suggest is that you make your own response (by putting a summary of those links to external websites).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.