3kbest 3kbest - 5 months ago 44
Python Question

Python Convert binary String to binary int

I use the following function to convert an int number to become binary. While adding additional zeros (16 bit). But the result comes in binary string, which creates problems for me when I use it in an if statement with "Bitwise left-shifting and bitwise AND operator".

def binary(num, length=16):
return format(num, '#0{}b'.format(length + 2))

The function used in context:

if (binary(1024) & (1<<2)):
print "Bit 2 is SET"

But get the following error message:

Traceback (most recent call last):
File "log.py", line 209, in <module>
if (binary(1024) & (1<<2)):
TypeError: unsupported operand type(s) for &: 'str' and 'int'

Simply explained:

"0b0000010000000000" to be: 0b0000010000000000

Are there any simple solutions to this?

Answer Source

When ever you use any bitwise operators on a number , it automatically applies it as we would usually visualize the operation being performed on a binary value .

In your case , you can simply convert the string to integer first and then if u want you can also get the binary representation of the same number using the bin( ) function which returns a string in the binary represention.

Here is the code :-

numstring = "15"

num_in_base_10 = int(numstring)
string_in_binary_form = bin(num_in_base10)

#If you dont want the 0b prefix of the binary repr , you can simple do , 

string_in_binary_form.replace('0b','') which would return the string without 0b prefix.