Zoralikecury
Zoralikecury

Reputation: 39

Change string to binary then write it to a file

Currently I have to write a string of binary to a file --- however, I need to write it in binary. For example I am given the string s = "1011001010111". I want to be able to write this to a file in binary format. So as a result the file will when I hexdump it will have the binary output of: 1011001010111. I have thought about iterating through my string s character by character to obtain which bit value, however i am having issues writing it out in binary format to the file.

Edit: my code

bits2 = "000111010001110100011110000111110101"
int_value = int(bits[1::], base=2)
bin_array = struct.pack('i', int_value)
f = open("test.bnr", "wb")
f.write(bin_array)

Upvotes: 0

Views: 183

Answers (1)

Carlo Zanocco
Carlo Zanocco

Reputation: 2019

Because your answer is a little bit confused I use as example string: "1011001010111".

This is the code to write the string to the binary file.

import struct 

bits = "1011001010111"
int_value = int(bits,2) # Convert the string to integer with base 2
bin_array = struct.pack('>i', int_value) # Pack the int value using a big-endian integer

with open("test.bnr", "wb") as f: # open the file in binary write mode
    f.write(bin_array) # write to the file

According to the documentation of the struct module you can see that you need the > with the i.

You have two different ways to dump the file, using the unix terminal:

hexdump -e '2/1 "%02x"' test.bnr

But here you will get the hexadecimal number, and later you need to convert it.

Or you can use this script that read the file and print out the binary string.

with open('test.bnr', 'rb') as f:
    for chunk in iter(lambda: f.read(32), b''):
        print str(bin(int(chunk.encode('hex'),16)))[2:]

As expected from your question using the string "1011001010111" you receive the same string reading it back from the file.

Using the second string ("000111010001110100011110000111110101") you get an error:

'i' format requires -2147483648 <= number <= 2147483647

This is because the 'i' option is not correct for this number. Converting this value to int you receive 7815160309. The number is too big for an integer.

Here you need to use the '>Q' or '>q'.

Upvotes: 1

Related Questions