Understanding Binary and Hexadecimal Numbers by Writing Python Code

Rhett Allain
10 min readJul 8, 2023
Photo: Rhett Allain. Binary to Decimal and Hexadecimal to Decimal

There’s a classic joke. It goes like this:

There are 10 kinds of people that understand binary….

I mean, it’s just sort of funny but I still like it. Why do you need to know about binary numbers? Uncle Owen (from Star Wars) is looking for a droid that understands the binary language of moisture vaporators (which C3PO says he understands). However, in the real world binary is the number system that computers like to use.

In this post, I’m going to look at the following three number systems:

  • Decimal. You already know this system. It’s the set of 10 numbers, from 0–9. Oh, look — your hands also have 10 digits. Wow.
  • Binary. This number system only has two numbers. That are 1 and 0.
  • Hexadecimal. This has 16 numbers. We use 0–9 plus A, B, C, D, E, F (since we ran out of decimal numbers).

I’m going to show how to convert from binary to decimal (and back) and then the same for hexadecimal. Although you can use built in functions in python, we are going to write some code mostly from scratch (because it will be fun).

Base 10 Numbers

If you want to understand binary, you have to first understand the decimal system. Suppose you…

--

--

Rhett Allain
Rhett Allain

Written by Rhett Allain

Physics faculty, science blogger of all things geek. Technical Consultant for CBS MacGyver and MythBusters. WIRED blogger.

No responses yet