In: Computer Science
PYTHON: How do I split up the binary string into chunks of 8 so that they are converted from binary to ASCII characters? For example "0011101000101001" would be eventually converted to ":)" . The code I have below is what I currently have. It currently only works for binary strings of 8. argv[1] is the text file it is reading from and argv[2] is basically just 8.
import sys
filename=sys.argv[1]
length = int(sys.argv[2])
message_data = open(filename, "r")
message_text = message_data.read()
if len(message_text) == 0:
sys.exit(1)
a= message_text.replace(',','')
a= ''.join(a.split())
conversion_list =[128, 64, 32, 16, 8, 4, 2, 1]
dec=0
for position, digit in enumerate((a)):
dec += conversion_list[position]* int(digit)
print("Decimal is ",dec)
e=chr(dec)
import sys
# it will split string with into give length
# and return list of string
def splitString(s, length):
return list((s[0+i:length+i] for i in range(0, len(s),
length)))
filename=sys.argv[1]
length = int(sys.argv[2])
message_data = open(filename, "r")
message_text = message_data.read()
if len(message_text) == 0:
sys.exit(1)
a= message_text.replace(',','')
# get splited list
a= splitString(a, length)
# you can uncomment it to see the list of splited string
# print(a)
conversion_list =[128, 64, 32, 16, 8, 4, 2, 1]
for i in range(len(a)):
dec = 0 # assume initial decimal equuvalent is
zero
# scan the entire 8 length str
for j in range(len(a[i])):
# getting equivalent decimal
dec = dec +
conversion_list[j]*int(a[i][j])
# printing equivalent decimal
# you can uncomment these to see decimal value
# print("Decimal is ",dec)
e=chr(dec)
print(e, end="")
print()