Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a string of 1's and 0's to a binary file?

Tags:

java

python

c

bash

I want to take a string of 1's and 0's and convert it into an actual binary file(simply writing the string of 1's and 0's to a file would just make it either ascii file containing "00110001"s and "00110000"s ). I would prefer to do this in python or directly from a bash shell, but java or C is fine too. this is probably a one time use.

Thanks.

like image 267
UserZer0 Avatar asked Sep 03 '11 03:09

UserZer0


People also ask

Are binary files 1 and 0?

Binary is a base-2 number system invented by Gottfried Leibniz that's made up of only two numbers or digits: 0 (zero) and 1 (one). This numbering system is the basis for all binary code, which is used to write digital data such as the computer processor instructions used every day.


1 Answers

In Python, use the int built-in function to convert the string of 0s and 1s to a number:

>>> int("00100101", 2)
37

Then use the chr built-in to convert a 8-bit integer (that is, in the inclusive range 0-255) to a character.

>>> chr(_)
'%'

The result of chr can be simply written to a file (opened in binary mode) with the file.write method.

like image 97
Eli Bendersky Avatar answered Sep 23 '22 04:09

Eli Bendersky