blog
blog copied to clipboard
General number bases (binary, octal, decimal, hex...)
Numbers can use nearly any base, such as base 5 or base 17. Popular bases are:
- 2: Binary, due to computers using 0's and 1's
- 8: Octal, which can compactly represent binary (each octal digit represents three bits) Ex: 101010 binary is 54 octal. 1012 = 58 , 0102 = 28
- 16: Hexadecimal (hex), which can compactly represent binary (each hex digit represents four bits). 0000 is 0, 0001 is 1, 0010 is 2, ..., 1110 is E, and 1111 is F.
- 10: Decimal, due to humans having ten fingers.
1. From any base to decimal
Converting from any base to decimal is straightforward: Each digit's decimal value is multiplied by each digit's decimal weight, and summed.
Examples:
Base 2 (binary) to decimal:
1111111 = 1 * 27 + 1 * 26 + 1 * 25 + 1 * 24 + 1 * 23 + 1*22 + 1 * 21 + 1 * 20 = 255
Base 8 (octal) to decimal:
107 = 1*82 + 0 * 81 + 7 * 80 = 64 + 0 + 7 = 71
Base 16 (hexadecimal) to decimal:
2b = 2* 161 + 11 * 160 = 32 + 11 = 43
2. From decimal to any base
Converting from decimal to any base can be done using a simple algorithm. The decimal is divided by the base, and remainder put in the rightmost digit. The process repeats with the quotient and the next digit, until the quotient is 0.
Examples:
Decimal to Base 2 (binary):
1310:
13 ÷ 2 = 6...1 6 ÷ 2 = 3...0 3 ÷ 2 = 1...1 1 ÷ 2 = 0...1
= 11012
Decimal to Base 5:
7310:
73 ÷ 5 = 14...3 14 ÷ 5 = 2...4 2 ÷ 5 = 0...2
= 3425
3. Any base to any base
To convert a number in any base B directly to any other base C, a straightforward approach first converts the base B number to a decimal number, then converts that decimal number to base C.
Example:
To convert 3205 to base 8, one starts with 3205 = 3×52 + 2×51 +2×50 = 8510 followed by converting to base 8: 85 ÷ 8 = 10 remainder 5, 10 ÷ 8 = 1 remainder 2, 1 ÷ 8 = 0 remainder 1, so concatenating yields 1258