Mhd Ghd
Mhd Ghd

Reputation: 35

convert a text file contain data in binary representation (only 0&1) to .bin file in python

I have a text file contains only zeros and ones each 32 bits in one line here is a sample :

00001111110000010000010100010111
00000010000001010000010100010011
00000000100000000000010110010011
00000000000000000000001100010111

I want to convert this file to .bin file using python , I have searched I saw people converting from data to bin file but this ffile is already zeros and ones.

thank you all.

Upvotes: 0

Views: 1289

Answers (2)

Leo Wotzak
Leo Wotzak

Reputation: 194

You can open the text file for reading and then create a binary file for writing using the open() function. Then you create a byte array from the text file (encoded for utf8) and write it to the binary file.

with open("binary.txt", "r") as textfile:
    with open("binary.bin", "w+b") as binfile:
        binfile.write(bytearray(textfile.read(), 'utf8'))

Upvotes: 1

ForceBru
ForceBru

Reputation: 44838

You can parse a string to an integer treating the string as a number written in binary using int:

integers = [
    int(line, 2)
    for line in your_file
]

In your case, integers will be [264307991, 33883411, 8390035, 791]. Then retrieve their binary representation with int.to_bytes:

>>> [i.to_bytes(4, 'little') for i in integers]
[b'\x17\x05\xc1\x0f', b'\x13\x05\x05\x02', b'\x93\x05\x80\x00', b'\x17\x03\x00\x00']

Then write these bytes to the other file:

with open("file.bin", "wb") as out:
    for i in integers:
        out.write(i.to_bytes(4, 'little'))

Upvotes: 1

Related Questions