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

1

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

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

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

# 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(???)
    
asked by anonymous 29.09.2015 / 03:31

1 answer

1

In Stack Overflow in English you have an answer .

Then your loop would be (I limited the maximum but test that 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'

Do not worry about b'\t' because they are special characters well known.

    
30.09.2015 / 01:58