Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: String of 1s and 0s -> binary file

Tags:

python

binary

I have a string of 1's and 0's in Python and I would like to write it to a binary file. I'm having a lot of trouble with finding a good way to do this.

Is there a standard way to do this that I'm simply missing?

like image 448
sevandyk Avatar asked Oct 11 '11 21:10

sevandyk


People also ask

How do you get a binary string of a number in Python?

Use bin() Function to Convert Int to Binary in Python In Python, you can use a built-in function, bin() to convert an integer to binary. The bin() function takes an integer as its parameter and returns its equivalent binary string prefixed with 0b .

How do I encode strings to binary in Python?

To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .

How do you convert binary to string?

The naive approach is to convert the given binary data in decimal by taking the sum of binary digits (dn) times their power of 2*(2^n). The binary data is divided into sets of 7 bits because this set of binary as input, returns the corresponding decimal value which is ASCII code of the character of a string.

How do you decode a binary file in Python?

You can open the file using open() method by passing b parameter to open it in binary mode and read the file bytes. open('filename', "rb") opens the binary file in read mode. b – To specify it's a binary file. No decoding of bytes to string attempt will be made.


3 Answers

If you want a binary file,

>>> import struct
>>> myFile=open('binaryFoo','wb')
>>> myStr='10010101110010101'
>>> x=int(myStr,2)
>>> x
76693
>>> struct.pack('i',x)
'\x95+\x01\x00'
>>> myFile.write(struct.pack('i',x))
>>> myFile.close()
>>> quit()
$ cat binaryFoo
�+$

Is this what you are looking for?

like image 143
Lelouch Lamperouge Avatar answered Oct 04 '22 05:10

Lelouch Lamperouge


In [1]: int('10011001',2)
Out[1]: 153

Split your input into pieces of eight bits, then apply int(_, 2) and chr, then concatenate into a string and write this string to a file.

Something like...:

your_file.write(''.join(chr(int(your_input[8*k:8*k+8], 2)) for k in xrange(len(your_input)/8)))
like image 38
liori Avatar answered Oct 04 '22 06:10

liori


There is a bitstring module now which does what you need.

from bitstring import BitArray

my_str = '001001111'
binary_file = open('file.bin', 'wb')
b = BitArray(bin=my_str)
b.tofile(binary_file)
binary_file.close()

You can test it from the shell in Linux with xxd -b file.bin

like image 32
TheMeaningfulEngineer Avatar answered Oct 04 '22 05:10

TheMeaningfulEngineer