Numeral systems in Python

Dr. Huidae Cho
Institute for Environmental and Spatial Analysis...University of North Georgia

1   Numeral systems

  • Decimal: Base 10 where $0\leq\text{one place}\leq 9$
  • Binary: Base 2 where $0\leq\text{one place}\leq 1$
  • Octal: Base 8 where $0\leq\text{one place}\leq 7$
  • Hexadecimal: Base 16 where $0\leq\text{one place}\leq 15$
    • Since a number greater than 9 takes up two places, we use A–F for 10–15, respectively.
    • For example, A is 10 and F is 15.

1.1   Conversion from decimal to binary

Let’s say we have a decimal number $x$ and want to convert it to a binary number. Follow these steps:

  1. Divide $x$ by $2$ and assign its quotient to $q$ and remainder to $r$. This $r$ takes the $2^0$'s place.
  2. Divide $q$ (from the previous step) by $2$ and assign its quotient to $q$ and remainder to $r$ (overwrite them). This new $r$ takes the $2^1$'s place.
  3. Repeat step 2 until $q$ becomes $0$. Each $r$ takes the next higher $2^n$'s place.

For example, $x=53$ and $y$ is the desired binary number.

  1. Divide 53 by 2: $q=26, r=1, y=1$
  2. Divide 26 by 2: $q=13, r=0, y=01$
  3. Divide 13 by 2: $q=6, r=1, y=101$
  4. Divide 6 by 2: $q=3, r=0, y=0101$
  5. Divide 3 by 2: $q=1, r=1, y=10101$
  6. Divide 1 by 2: $q=0, r=1, y=110101$
    • Here, you can actually save one step by placing $q=1$ from step 5 in the $2^5$'s place.

So the binary number for 53 is 110101.

1.1.1   A table method

$q$$r$
253
2261
2130
261
230
1*1

In this method, you can stop when $q$ becomes smaller than your target base 2. Now, collect all 1s and 0s starting from the last $q$ (*) from left to right. That is, 1, 1, 0, 1, 0, and 1. You get 110101.

1.2   Conversion from binary to decimal

Now, we want to go back from 110101 to 53. The right-most 1 is in the $2^0$'s place (ones place) while the left-most 1 in the $2^5$'s place (32s place). Starting from the $2^0$'s place, we complete this table:

BinaryPlaceDecimal
120$1\times2^0=1$
021$0\times2^1=0$
122$1\times2^2=4$
023$0\times2^3=0$
124$1\times2^4=16$
125$1\times2^5=32$

The sum of the Decimal column is 53.

1.3   Other conversions

Conversions between other numeral systems are exactly the same except that you have to use the appropriate base number instead of 2 in the above examples for binary conversions.

1.4   Python syntax

  • Decimal: 53
  • Binary: 0b110101
  • Octal: 0o65
  • Hexadecimal: 0x35

2   Homework: Conversions between numeral systems

  1. Convert a decimal number 2803 to
    • binary,
    • octal, and
    • hexadecimal.
  2. Convert a hexadecimal number 0xa2 to
    • decimal,
    • binary, and
    • octal.

Show your full work. You’ll get a zero if you just show me the correct answers.