I have to work using binary formated numbers and I'm wondering if there's a simple and easy built in way to use them. I am aware of the bytearray
but it works with byte type and it is absolutely not intuitive (at least for me).
So, is there any way of handling binary numbers (assign them to a variable, perform bit operations, transform to ASCII, etc.) easily? If not built in, at least a nice and understandable module.
Just in case what I'm asking is not clear enough, here is an example of what I picture a nice way for handling binary would be:
bin_num1 = Binary('100')
bin_num2 = Binary(0)
print(bin_num1.and(bin_num2)) # Prints 000
I'm using Python 3.6 but any solution in any version would do the job.
Edit 1:
As pointed out in the comments, 0bXXX
could work to get a type int
from a binary just as bin()
would do the opossite. Still, this would be working with integers, the result returned would be an integer and character conversion (e.g. bin('a')
) would be an error and require further conversions (from str to int and then to binary).
Assign binary numbers to a variable: You can use integer variables to hold the binary values. They can be created from the binary representation using the 0b
prefix.
x = 0b110 # assigns the integer 6
Perform bit operations: The bit operations &
(and), |
(or), ^
(xor), ~
(not) can be used on integers and perform the respective binary operations.
x = 0b110
y = 0b011
z = x & y # assigns the integer 0b010 (2)
Transform them to ASCII: To convert a number to ASCII you can use chr
.
x = 0b1100001 # assigns 97
print(chr(x)) # prints 'a'
Transform from ASCII: If you use integers to represent the binary values you can use ord
to convert ASCII values.
s = 'a'
x = ord(a) # assigns the integer 0b1100001 (97)
Print integer in binary: An integer can be printed in binary using the string format method on the string "{0:b}"
.
x = 0b1100001
s = "{0:b}".format(x)
print(s) # prints '1100001'
If you do not mind the 0b
prefix you can also use bin
.
x = 0b1100001
s = bin(x)
print(s) # prints '0b1100001'
Read integer from binary string: The int
function allows you to specify a base that is used when parsing strings.
x = int("1100001", 2) # assigns the integer 0b1100001 (97)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With