Numeral Systems
We’re used to counting in the decimal numeral system, which uses 10 digits: 0 through 9. This system likely developed because humans counted on their fingers, and most people have 10 fingers. But other number systems exist. Computers make use of binary, a numeral system with only two digits, 0 and 1. Programmers also sometimes use hexadecimal, which is a base-16 numeral system that uses the digits 0 to 9 but also extends into the letters A to F.
We can represent any number in any numeral system, and this program displays a range of numbers in decimal, binary, and hexadecimal.
numeral_systems.py
1"""Numeral System Counters, by Al Sweigart al@inventwithpython.com
2Shows equivalent numbers in decimal, hexadecimal, and binary.
3This code is available at https://nostarch.com/big-book-small-python-programming
4Tags: tiny, math"""
5
6
7print('''Numeral System Counters, by Al Sweigart al@inventwithpython.com
8
9This program shows you equivalent numbers in decimal (base 10),
10hexadecimal (base 16), and binary (base 2) numeral systems.
11
12(Ctrl-C to quit.)
13''')
14
15while True:
16 response = input('Enter the starting number (e.g. 0) > ')
17 if response == '':
18 response = '0' # Start at 0 by default.
19 break
20 if response.isdecimal():
21 break
22 print('Please enter a number greater than or equal to 0.')
23start = int(response)
24
25while True:
26 response = input('Enter how many numbers to display (e.g. 1000) > ')
27 if response == '':
28 response = '1000' # Display 1000 numbers by default.
29 break
30 if response.isdecimal():
31 break
32 print('Please enter a number.')
33amount = int(response)
34
35for number in range(start, start + amount): # Main program loop.
36 # Convert to hexadecimal/binary and remove the prefix:
37 hexNumber = hex(number)[2:].upper()
38 binNumber = bin(number)[2:]
39
40 print('DEC:', number, ' HEX:', hexNumber, ' BIN:', binNumber)