Convert binary to ASCII and vice versa

前端 未结 8 1142
余生分开走
余生分开走 2020-11-22 03:22

Using this code to take a string and convert it to binary:

bin(reduce(lambda x, y: 256*x+y, (ord(c) for c in \'hello\'), 0))

this outputs:<

8条回答
  •  你的背包
    2020-11-22 04:17

    I'm not sure how you think you can do it other than character-by-character -- it's inherently a character-by-character operation. There is certainly code out there to do this for you, but there is no "simpler" way than doing it character-by-character.

    First, you need to strip the 0b prefix, and left-zero-pad the string so it's length is divisible by 8, to make dividing the bitstring up into characters easy:

    bitstring = bitstring[2:]
    bitstring = -len(bitstring) % 8 * '0' + bitstring
    

    Then you divide the string up into blocks of eight binary digits, convert them to ASCII characters, and join them back into a string:

    string_blocks = (bitstring[i:i+8] for i in range(0, len(bitstring), 8))
    string = ''.join(chr(int(char, 2)) for char in string_blocks)
    

    If you actually want to treat it as a number, you still have to account for the fact that the leftmost character will be at most seven digits long if you want to go left-to-right instead of right-to-left.

提交回复
热议问题