Python Forum
HELP: String of Zero's and One's to binary byte
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
HELP: String of Zero's and One's to binary byte
#2
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
Reply


Messages In This Thread
RE: HELP: String of Zero's and One's to binary byte - by heiner55 - May-19-2019, 07:31 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Add one to binary string uwl 2 949 Sep-11-2022, 05:36 PM
Last Post: uwl
  [HELP] string into binary ZeroPy 2 2,060 Dec-31-2020, 08:15 PM
Last Post: deanhystad
  'utf-8' codec can't decode byte 0xe2 in position 122031: invalid continuation byte tienttt 12 11,522 Sep-18-2020, 10:10 PM
Last Post: tienttt
  'utf-8' codec can't decode byte 0xda in position 184: invalid continuation byte karkas 8 31,655 Feb-08-2020, 06:58 PM
Last Post: karkas
  hex file to binary or pcap to binary baran01 1 5,689 Dec-11-2019, 10:19 PM
Last Post: Larz60+
  First Byte of a string is missing while receiving data over TCP Socket shahrukh1987 3 4,232 Nov-20-2019, 10:34 AM
Last Post: shahrukh1987
  Byte string catenation inefficient in 3.7? RMJFlack 13 5,664 Aug-18-2019, 05:19 AM
Last Post: RMJFlack
  CSV file from Binary to String mr_byte31 2 13,538 Jul-27-2019, 08:46 PM
Last Post: snippsat
  binary search string help kietrichards 1 2,205 Mar-08-2019, 12:43 PM
Last Post: stullis
  converting binary b'0x31303032\n' to "1002" string amygdalas 2 2,637 Nov-07-2018, 03:50 AM
Last Post: amygdalas

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020