Binary, Hex, and Octal in Python. A stroll outside the decimal system | by Rod Castor | Towards Data Science

Python is known for being powerful and easy to use when it comes to math. Both its native capabilities and resourceful libraries like NumPy, Pandas, or Scikit-learn, provide developers with the necessary tools for heavy lifting numbers. But sometimes we need to step outside the decimal world and work with one of the other common number bases.
A number base is the number of digits that a system of counting uses to represent numerical values. The most prevalent number system is the decimal system, also known as base 10. In decimal, the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 represent every possible value. But computers and software developers often need to use other bases.
towardsdatascience.com
Of all its cousins, the decimal system invites binary, hexadecimal, and octal over for dinner the most. The others fall into that special category of cousin you avoid when you’re with friends. However, if you plan on using binary, hexadecimal, or octal you may need to brush up on your Python. They are not as clean and easy to use in Python as base 10.
Binary only uses the digits 0 and 1. From these two, it can account for every possible value, the same a the decimal system. Do you remember place values from grade school? That’s exactly how it works. In decimal, every place increases by a multiple of ten, but in binary, every position increases by a multiple of two.
For example, 101 would represent a value of 5.
And 10101 would represent a value of 21.
Ever wonder why your network subnet mask looks something like 255.255.255.0? Because each of those numbers separated by a period is made up of an eight-digit binary number, 11111111.
We could have started this section by stating, “Binary only uses 10 digits.” If you don’t get the joke, read the explanation of how binary works again.
In Python, using binary numbers takes a few more steps than using decimal numbers. When you enter a binary number, start with the prefix ‘0b’ (that’s a zero followed by a minuscule b).
0b11is the same as binary 11, which equates to a decimal 3. It’s not hard, but it is extra work. Whenever you want to store a binary value in a variable, it will convert it to decimal for you.
number1 = 0b11
This results in the variable number1 storing a value of three. It just stores the value without indicating you’d like it represented in binary. So, when you retrieve it, you’ll get a decimal value of 3. Truthfully, Python processes all the mathematical operators independent of base, but it always returns them to you in decimal.
“But what if I want to have my numbers returned to me in binary?”
Glad you asked.
If you’d like to keep numbers in your code strictly binary, here’s a solution.
>>> num1 = "0b100">>> num2 = "0b110">>> mysum = int(num1, 2) + int(num2, 2)>>> print(bin(mysum))0b1010
In the code snippet above, we started by assigning a string of “0b100” to the variable num1. Next, we assigned a string of “0b110” to the variable num2. So we have two variables of type string storing the binary representation of 4 and 6, respectively.
Next, we added the two numbers. But as we did that, we converted each to an integer in base 10 using the function int(). Normally int() would throw an error given a string with a letter in it. By specifying the second parameter of 2, we instruct int() to interpret the string as a binary number. So, it stays happy.
You can use the second parameter to specify any base between 2 and 36. Bases 2 and 36 are included in the range.
towardsdatascience.com
After we add the two numbers together and store the result in mysum, we print the sum. But it’s been stored independent of base. When we recall it, it still wants to present it to us in decimal. So we must tell Python we want our number in binary. Using the bin() function converts the value to binary before it’s printed to the screen.
The above code gives you a clear representation of binary in Python. However, you may also use a more abbreviated version, like this.
>>> num1 = 0b100>>> num2 = 0b110>>> mysum = num1 + num2>>> print(bin(mysum))
You get the same result. The sole difference is how you are storing the numbers in variables num1 and num2. If you print either variable to the screen in the first example, you will see it in binary even though it’s technically a string. In the second example, you will see a decimal unless you use bin() to convert it.
>>> num1 = "0b100">>> print(num1)"0b100">>> num1 = 0b100>>> print(num1)4>>> print(bin(num1))0b100
Decimal uses ten digits, binary uses two digits, and hexadecimal uses sixteen digits. Since we only have the ten digits from the decimal system to use, we substitute letters for everything above the number nine. Therefore, the digits in hexadecimal are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. They represent zero through nine, then A is worth ten, B is worth eleven, C is worth twelve, D is worth thirteen, E is fourteen, and F wraps up with a value of fifteen. So, there are sixteen digits in hexadecimal. If you write that in hexadecimal, you can state, “Hexadecimal has 10 digits.”
Wait? Haven’t we seen that before? Yes. Honestly, a ‘10’ always represents the total number of digits in any base if you are writing the number in the respective number system. But it’s only funny in binary.
When denoting hexadecimal numbers in Python, prefix the numbers with ‘0x’. Also, use the hex() function to convert values to hexadecimal format for display purposes.
Our two hexadecimal code samples are similar to the ones we used for binary.
>>> hnum1 = "0x10">>> hnum2 = "0x10">>> myhsum = int(hnum1, 16) + int(hnum2, 16)>>> print(hnum1)"0x10">>> print(myhsum)32>>> print(hex(myhsum))0x20>>> hnum1 = 0x10>>> hnum2 = 0x10>>> myhsum = hnum1 + hnum2>>> print(hnum1)16>>> print(myhsum))32>>> print(hex(myhsum))0x20
Finally, the same holds for octal. Any guesses on how many digits are in the octal number system? Octal stands for eight. Right, octal contains eight digits. And instead of bin() or hex(), we use oct() to convert numbers to octal in Python. We prefix octal numbers with a zero followed by a lowercase o, like ‘0o’.
The eight digits of octal are 0, 1, 2, 3, 4, 5, 6, 7.
Let’s use the same code sample here, but we’ll use the proper notation and conversion function for octal.
>>> onum1 = "0o10">>> onum2 = "0o10">>> myosum = int(onum1, 8) + int(onum2, 8)>>> print(onum1)"0o10">>> print(myosum)16>>> print(oct(myosum))0o20>>> onum1 = 0o10>>> onum2 = 0o10>>> myosum = onum1 + onum2>>> print(onum1)8>>> print(myosum))16>>> print(oct(myosum))0o20
The great thing about Python is it can do nearly everything except my laundry. And I’m working on that.
The takeaways are simple:
Binary uses bin() and ‘0b’.
Hexadecimal uses hex() and ‘0x’.
Octal uses oct() and ‘0o’.
The int() function can be used to convert numbers into a base 10 integer from any base between 2 and 36 by changing the second parameter. e.g. int(number, 30)
Even though using bases outside our beloved decimal system requires a bit more effort, Python easily adapts and empowers us to go where no decimal has gone before — into the final frontier of other bases.
Rod Castor helps companies Get Analytics Right! He helps international organizations and small businesses improve their data analytics, data science, tech strategy, and tech leadership efforts. In addition to consulting, Rod also enjoys public speaking, teaching, and writing. You can discover more about Rod and his work at rodcastor.com and through his mailing list.