I have a letter, for example, the letter s
. I want to convert it to a binary 8-bit string and back. I have read many articles, but I don't really understand. Can someone help me?
You can use ord()
, chr()
and int()
:
def _bin(char):
return format(ord(char), '08b')
def _int(b):
return chr(int(b, 2))
print(_bin('A'))
print(_int('01000001'))
01000001
A
@SIGHUP: Use of format()
is functionally correct but most modern code would probably use f-strings - e.g., return f"{ord(char):08b}"
.