Python Forum
HELP: String of Zero's and One's to binary byte - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: HELP: String of Zero's and One's to binary byte (/thread-2755.html)



HELP: String of Zero's and One's to binary byte - schwasskin - Apr-07-2017

I have some code that I am using to convert a file to bytes then those bytes to strings of 0's and 1's.

with open(file, mode='rb') as file:
content = file.read()
b = bytearray(content)

for number in b:
   data = bin(number)[2:].zfill(8)
   print data
I get output like 10110100, 00000001, etc, etc as it should be.
I want to take those strings of bits I get in my output and convert them back to bytes, then write those bytes back to a new file.
I have tried with the following code:

list = ('11111111', '11111110', '01101000', '00000000', '01101001', '00000000', '00001101', '00000000', '00001010', '00000000')
def writer(stuff):
   blob = struct.pack('!H', int(stuff, 2))
   with open('test.txt', "a+b") as file:
           file.write(blob)
for strings in list:
   writer(strings)
The original text file contains the word "hi" and that is all, but when I write the new file the output is "▒▒hi"


RE: HELP: String of Zero's and One's to binary byte - heiner55 - May-19-2019

Your code is OK except "B" for "!H".
And you need an editor which is able to open
the file as UTF-16 with BOM.

#!/usr/bin/python3
import struct

lst = ('11111111', '11111110',
       '01101000', '00000000',
       '01101001', '00000000',
       '00001101', '00000000',
       '00001010', '00000000')

def writer(stuff):
   blob = struct.pack('B', int(stuff, 2))
   with open('test.txt', "a+b") as file:
       file.write(blob)

for strings in lst:
   writer(strings)
#done

Or without struct:

#!/usr/bin/python3
lst = ('11111111', '11111110',
       '01101000', '00000000',
       '01101001', '00000000',
       '00001101', '00000000',
       '00001010', '00000000')

def writer(stuff):
   blob = int(stuff, 2).to_bytes(1, byteorder='big')
   with open('test.txt', "a+b") as file:
       file.write(blob)

for strings in lst:
   writer(strings)
#done