Home > database >  How do I turn this list into a string?
How do I turn this list into a string?

Time:09-25

I'm trying to convert binary to decimal to ASCII. Using this code, I'm able to take a binary input and split it into chunks of 7 bits.

def binary_to_ascii7bits(bstring):
    n = 7
    byte = [bstring[i:i n] for i in range(0, len(bstring), n)]
    print(byte)

I need to be able to turn each 7-bit substring into a decimal number in order to use the chr function. If I try to turn this list into a string, it prints for example, "['1111000']", but I cannot have the brackets and apostrophes in the string. What can I do to fix this?

CodePudding user response:

First of all, for the chr function it should be an integer, not a decimal.

Add this list comprehension before the print function -

byte = [chr(64   int(i)) for i in byte]

This will give the string for the bytes. I think this is what you want.

CodePudding user response:

You can add just one more line (as below) to achieve what you described.

You have int(..., 2) to convert the string representation of a binary number into an integer. Then apply chr to get a character. This procedure is done using (list) comprehension, so that the result is a list of characters. Then use join to make a single string.

text = '1111000' * 10

def binary_to_ascii7bits(bstring):
    n = 7
    byte = [bstring[i:i n] for i in range(0, len(bstring), n)]
    return ''.join(chr(int(x, 2)) for x in byte)

print(binary_to_ascii7bits(text)) # xxxxxxxxxx
  • Related