0

How can i get return value after converting hex value to binary string?

I'm always getting string binary which is not useful for bit operation.

i.e bin(int(str('0x460001'), 16)) is always 0b10001100000000000000001, instead I want 0b10001100000000000000001 as my output.

For that binary value I want to perform an operation which requires non string value, like:

0b10001100000000000000001 | 0b10001100100000000000001

Please let me know if there is any option or library I can use for it.

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

Probably to your surprise the problem you see isn't a problem at all because:

print( type(0b10001100100011000000001) )

# gives: <class 'int'> (or int in Python 2) 

0b10001100100011000000001 IS a NUMBER, not a string ... so you can do binary operations directly with it.

Just try this:

print( 0x460001 == 0b10001100000000000000001 ) # gives True
print( 0x460001 == 4587521 )                   # gives also True
print( 4587521  == 0b10001100000000000000001 ) # gives True

or this:

print( type(0x460001), type(0b10001100000000000000001), type(4587521) )
# gives <class 'int'> <class 'int'> <class 'int'>

It doesn't matter HOW you write a number it will be the same number, but

print( "0x460001" == 0b10001100000000000000001 ) # gives False

will give you False as "0x460001" is a string not a number.

Anyway, until you understand the above, you can play around with following code snippets:

def bitwiseORforBinaryNumbers(bin1, bin2):
  return bin( bin1 | bin2 )

print( bitwiseORforBinaryNumbers(
   0b10001100000011000000001, 
   0b10001100100000000000001) )
#  0b10001100100011000000001

or just written directly:

print( 
  bin( 0b10001100000011000000001 | 
       0b10001100100000000000001 ) ) 
#      0b10001100100011000000001

The same for strings with binary representations of a number look like:

def bitwiseORforStringsWithBinaryValue(binStr1, binStr2):
  return bin(int(binStr1,2) | int(binStr2,2))

print( bitwiseORforStringsWithBinaryValue("0b10001100000011000000001", "0b10001100100000000000001") )
# gives:
0b10001100100011000000001

or just done directly in code:

print( bin( int("0b10001100000011000000001",2) | int("0b10001100100000000000001",2) ) )
Claudio
  • 7,474
  • 3
  • 18
  • 48