pythonbinaryconvertersletter

How to convert from string to 8-bit binary number and vice versa


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?


Solution

  • 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'))
    
    

    Prints

    01000001
    A
    

    Comment

    @SIGHUP: Use of format() is functionally correct but most modern code would probably use f-strings - e.g., return f"{ord(char):08b}".