Working with hexadecimal, binaries, and other bases is becoming common at work, at first we try to use custom functions to convert from and to some bases, especially hexadecimal. But other languages have built-in methods to do that conversion, and so python too.
First to convert and hexadecimal string to an integer we use:
int_number = int('ab1', 16)The variable int_number will be 2737. That is ab1 hex to integer conversion. Now what about the other way, integer to hexadecimal, that would be:
hex(int_number)
And that would return '0xab1'. Note that it returns a string and has the 0x notation, we could use that notation also in the first conversion like this:
int_number = int('0xab1', 16)So as you can see we pass a parameter to the int function to indicate the base, if we dont pass any python assumes that we are using a 10 base. As you have also seen there is a hex built-in function but there is no binary, or any other base built-in, so since we work a lot with binary we built a small function to do the work. There are hundreds of ways to do this, using recursion, whiles, fors, lamdas, etc. We end up using this function:
def dectobin(number):
if number < 1:
return ""
else:
return dectobin(number / 2) + str(number & 1)
Hope this works for you.