I'm trying to decode binary which are located in a .txt file, but I'm stuck. I don't see any possibilities this can go around.
def code(): testestest
ascii = {'01000001':'A', ...}
binary = {'A':'01000001', ...}
print (ascii, binary)
def encode():
pass
def decode(code,n):
f = open(code, mode='rb') # Open a file with filename <code>
while True:
chunk = f.read(n) # Read n characters at time from an open file
if chunk == '': # This is one way to check for the End Of File in Python
break
if chunk != '\n':
# Process it????
pass
How can I take the binary in the .txt file and output it as ASCII?
1 Answer 1
From your example, your input looks like a string of a binary formatted number.
If so, you don't need a dictionnary for that:
def byte_to_char(input):
return chr(int(input, base=2))
Using the data you gave in the comments, you have to split your binary string into bytes.
input ='01010100011010000110100101110011001000000110100101110011001000000110101001110101011100110111010000100000011000010010000001110100011001010111001101110100001000000011000100110000001110100011000100110000'
length = 8
input_l = [input[i:i+length] for i in range(0,len(input),length)]
And then, per byte, you convert it into a char:
input_c = [chr(int(c,base=2)) for c in input_l]
print ''.join(input_c)
Putting it all together:
def string_decode(input, length=8):
input_l = [input[i:i+length] for i in range(0,len(input),length)]
return ''.join([chr(int(c,base=2)) for c in input_l])
decode(input)
>'This is just a test 10:10'
answered Jan 28, 2016 at 14:17
tglaria
5,8962 gold badges15 silver badges17 bronze badges
Sign up to request clarification or add additional context in comments.
13 Comments
Musa
Thanks, but I think there need to be a dictionary for holding the mapping between binary string and ascii chars? This is the binary: 01010100011010000110100101110011001000000110100101110011001000000110101001110101011100110111010000100000011000010010000001110100011001010111001101110100001000000011000100110000001110100011000100110000
tglaria
Is that a question? No, you don't need it. you convert your binary string into an integer and then convert that integer into ascii.
Musa
Thanks, but the binary string is in an external file in a folder as mentioned.
tglaria
So? just load that string.
Musa
So in it will be... def code(): bin = int('0b110100001100101011011000110110001101111', 2) pass
|
lang-py
int("01000001', 2)to convert into integer and thenchr(65)to get char ?bin,int, andchr.