transform hex to binary and vice versa, but keeping them as integers

I know how to transform a hexadecimal integer into a binary string using the bin function, but is there an easy way to transform a hex integer into a binary integer?

Phrased differently, is there an easy way to transform the string representation of a binary integer ("0b111") into an integer representing a binary integer (0b111)

Using bin() results in a hexadecimal string

>>> bin(0x7)
'0b111'
>>> type(bin(0x7))
<class 'str'>

But what I want to achieve is this:

>>> magic(0x7)
0b111
>>> type(magic(0x7))
<class 'int'>

(The magic function is just a placeholder, essentially I want a way to transform the string representation of the binary integer into a binary integer)

  • Question 1: Is this somehow possible, if yes how?
  • Question 2: Does it make sense to do so? Is it better to work with string representations or integer representations of hexadecimal and binary numbers?

1 Answer

There is no difference between the what you call a 'hexadecimal integer', and a 'binary integer' - they are both just integers:

>>> 0x07
7
>>> 0b111
7
>>> type(0x07)
<type 'int'>
>>> type(0b111)
<type 'int'>
>>> 0x07 == 0b111
True
>>> 0x07 is 0b111 # This is true in the special case of small integers
True

The 0x or 0b prefix is just a way for you to tell the interpreter how to read the input you provided.

As for converting a binary string representation of an integer into an actual integer, you can do so with int(string, base):

>>> int('0b111', 2)
7
4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like