Try this:
int(s, base=2)
for example,
for i in ['10101', '11100', '11010', '00101']:
print(int(i, base=2))
@metatoaster also mentioned this.
Answer from 0__ on Stack OverflowHow do I convert a string of 1's and 0's to bits in the huffman compression algorithm?
python - Is there a way of converting a string of 1's and 0's to its binary counterpart, i.e. not ASCII - Stack Overflow
python - Turning binary data into a literal string of '0's and '1's - Stack Overflow
Python: String of 1s and 0s -> binary file - Stack Overflow
I'm trying to implement the hoffman algorithm in Python, but after converting the file contents to 1's and 0's I don't know how to convert them to smaller bits before writing to a file (for compression).
Basically what I'm doing now is just saving string characters to my text file, which is resulting a bigger file size.
with open('compressed.txt', 'wb') as f:
f.write(''.join([codeMap[letter] for letter in file]))Note on terminology: a binary literal is a piece of text, normally appearing in source code, so I've shown code that results in the same text, in a string object. A binary literal is not a number, but it evaluates to a number in Python code, so I've also shown code to calculate that number. 0b01101101 and 109 are different literals (one binary, one decimal), but when evaluated they give exactly the same result, an integer equal to one hundred and nine.
If you want to write the integer 109 as a single byte over a serial connection, then what you want to write is the single character with code 109, not a binary literal.
my_string = "01101101"
my_binary_literal = "0b" + my_string
my_string_converted_to_integer = int(my_string, 2)
my_single_character = chr(my_string_converted_to_integer)
assert my_single_character == 'm'
You can use argument base from string to int conversion:
int('01101101', base=2)
# output : 109
# (and 109 in base 10 = 01101101 in base 2)
And reverse action, use bin() to create the string with a 0b at the beginning:
bin(109)
# output : '0b01101101'
You could convert b'a' to its corresponding integer ord value, and then print the int in binary format using '{:b}'.format:
In [6]: '{:b}'.format(ord(b'a'))
Out[6]: '1100001'
Reading a large file one-byte-at-a-time can be very slow. You'll get better performance by reading more bytes per call to
f.read. You can iterate over the contents of the file in chunks of 1024 bytes using:with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(1024), b''):Similarly, calling
printonce for each byte can be very slow. You'll get better performance by printing more bytes per call toprint. So you could use a list comprehension to loop over the bytes inchunk, convert each to its string-binary format and then use''.jointo join the strings together:print(''.join(['{:b}'.format(ord(c)) for c in chunk]), end='')Use bare
exceptis considered a bad practice. If you choose to usetry..excepthere, list only those Exceptions you wish to handle:try: ... except IOError:
def slurpInstructions(filename):
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(1024), b''):
print(''.join(['{:b}'.format(c) for c in chunk]), end='')
In Python 3, to convert 2 bytes into a bitstring ('{:b}'.format() may be slightly slower):
>>> bin(int.from_bytes(b'\x00a', 'big'))[2:].zfill(16)
'0000000001100001'
For a single-source Python 2/3 compatible version, see Convert binary to ASCII and vice versa
To load all instructions both time- and space-efficiently, you could use array module:
#!/usr/bin/env python
import os
import sys
from array import array
instructions = array('H') # each instruction is >=2 bytes
n = os.path.getsize(filename) // instructions.itemsize # number of instructions
with open(filename, 'rb') as file:
instructions.fromfile(file, n) # slurp file
if sys.byteorder == 'little':
instructions.byteswap() # force big-endian order
for h in instructions: # print as bitstrings
print('{:016b}'.format(h))
For other ways to read a binary file efficiently, see Reading binary file in Python and looping over each byte.
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?
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)))
Let's say I input a as my variable. I want it to display 01100001
That's it. I've tried everything but for some reason micropython shits itself when I try to use conversion_binary = ''.join(format(ord(i), '08b') for i in lett)"
And yet normal Python works just fine. I don't get it. It just says that "format" isn't defined.
Python doesn't have a separate type for binary numbers when you type 0b1 there it just gets interpreted as base 2 and is still stored as a base 10 integer at the end so for converting from a string '0b1' you can just convert it to int while telling it that the value is in base 2
y = '0b1'
print(int(y, 2))
the bin function also just gives you a binary representation of the integer as a string
You can try something like this : -
x = "0b1"
y = 0b1
#type of x and y before change
print(type(x))
print(type(y))
x,y=y,x
print(bin(x))
print(y)
#type of x and y after change
print(type(x))
print(type(y))
This will convert each byte in your string to 8 binary digits and separate them with a space. You can easily change the separator.
data = " ".join(bin(ord(b))[2:].rjust(8, "0") for b in data)
Use with so you don't have to explicitly close the fh
with open('test.txt','w') as fh:
fh.write("".join(bin(ord(x))[2:].zfill(8) for x in data)
If the file is large, the above will use a lot of memory, instead you should read data in smaller chunks and call write() multiple times
Aside:
fh.close is just a reference to the method that closes the file. To call the method (ie close the file) you do need to say fh.close()
I want a function that takes for example 'Hello brother! 😊'(a combination of any unicode symbols) as input and outputs the binary equivalent using utf-8 so here:
'01001000 01100101 01101100 01101100 01101111 00100000 01100010 01110010 01101111 01110100 01101000 01100101 01110010 00100001 00100000 11110000 10011111 10011000 10001010'
The output should also be a string.
I want to write a function that takes the path of a file and returns a string of 1s and 0s that can later be converted back into the original file. I've tried using the base64 module on an image file, but it gives me a string full of weird symbols, like what you would see if you opened the image in a text editor.
with open(file_path, "rb") as contents:
converted_string = base64.b64encode(contents.read())
print(converted_string)I want only 1s and 0s. How can I do so?
Edit: Making my question clearer.