0

I have a dilemma where I have a string of binary code that is all one line. Like this 0110000101110000011100000110110001100101 (or apple), but I need a way to read every 8 characters to form the full code for the letter so I can convert it.

For some background on how I store the binary, I store it in a dict with the keys as the letters and binary as a string: binary = {"a": "01100001"}, later I swap the keys and values. I can't find a way to read the string in 8 characters chunks like so 01100001 = a or 01100101 = e, but it has to happen all at once in a for a loop.

def binary_string(bin):
    res = dict((v, k) for k, v in binary.items())
    data = []
    for bit in bin:
        if bit in res:
            data.append(res[bin])
        else:
            print("Couldn't find " + bit + "'s letter")
    load = str(data).strip("[]")
    return load

I am looking for a way to say: for every 8 characters in this string: append the letter equivalent to a list, and from there I have no problem creating the output to my desire.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • 3
    `int()` takes an optional `base` argument, `chr()` converts the resulting int to a string, and it is trivial to use slices to step through a string in chunks of size 8. A king of Python should be able to take it from there. – John Coleman Jul 20 '19 at 23:33
  • I'd recommend to use bitstring package https://pypi.org/project/bitstring/ You treat your binary string as BitArray and iterate over it with 8 bits step. So no need to keep ASCII table in the dictionary. – Yuri Ginsburg Jul 21 '19 at 00:15
  • The duplicate I chose isn't an exact match, but it seems to address the one part of the problem you actually need help with :) – Karl Knechtel Jul 21 '19 at 01:53

1 Answers1

3

If you already have a dictionary to map those values, like this:

char_map = {
    "01100001": "a",
    "01100010": "b",
    # ...
}

then you can simply split the string in chunks of 8 characters and look the letters up in the dictionary:

def binary_string(bin):
    return ''.join(char_map[bin[i:i+8]] for i in range(0, len(bin), 8))

Otherwise, a general solution that doesn't involve the use of any dictionary is to just parse the binary values into integers (using int('...', 2) to transform from base 2):

def binary_string(bin):
    return ''.join(chr(int(bin[i:i+8], 2)) for i in range(0, len(bin), 8))

Result:

>>> binary_string('0110000101110000011100000110110001100101')
'apple'
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128