Base N Conversion

Purpose:
1. Knowing to convert Base N is a need for programming
2. To be able to convert Floating point numbers back and forth
3. Bit Manipulation in any application (logic)
4. Optimization
5. Debugging

  • Important conversion to know for Programming:
    • HEX (Base 16) Base: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F, A=10, B=11, C=12, D=13, E=14, F=15
    • OCT (Base 8) = Base: 0,1,2,3,4,5,6,7
    • DEC (Base 10) = Base: 0,1,2,3,4,5,6,7,8,9
    • BIN (Base 2) = Base: 0,1

Convert DEC to ANY Base N

Convert Base 10 to Base 2 by Division Example:
2 | 20 | (Setting Up)
10 | 0 (20 / 2 = 10 remainder 0)
5 | 0 (10 / 2 = 5 remainder 0)
2 | 1 (5 / 2 = 2 remainder 1)
1 | 0 (2 / 2 = 1 remainder 0)
    1 (1 < 2, stop) 
BIN = 10100 (Concat Remainders from bottom up)


Convert Base 10 to Base 3 by Division Example:
3 | 20 | (Setting Up)
        6 | 2 (20 / 3 = 6 remainder 2)
        2 | 0 (6 / 3 = 2 remainder 0)
2 (2 < 3, stop)
Base 3 = 202 (Concat Remainders from bottom up)


Convert Base 10 to OCT by Division Example:
8 | 20 | (Setting Up)
        2 | 4 (20 / 8 = 2 remainder 4)
        2 (2 < 8, stop)
OCT = 024 (Concat Remainders from bottom up)
NOTE: THE 0 in front represent the number as an OCT base 8


Convert Base 10 to HEX by Division Example:
16 | 20 | (Setting Up)
          1 | 4 (20 / 16 = 1 remainder 4)
          1 (1 < 16, stop)
HEX = 0x14 (Concat Remainders from bottom up)
NOTE: the 0x in front represent the number as a HEX base 16

Convert DEC to ANY Base N

Convert Base 2 to DEC by Division Example: Given BIN = 10100
Starting from LEAST significant bit:
1 0 1 0 0
1 * 2^4  + 0 * 2^3  + 1 * 2^2 +  0 * 2^1 + 0 * 2^0
= 16 + 0 + 4 + 0 + 0 = 20

Binary (base 2)number * baseN ^ bit positionResult (sum all together)
00 * 2^00
00 * 2^10
11 * 2^24
00 * 2^30
11 * 2^416
DEC = 16 + 0 + 4 + 0 + 0 = 20

Convert Base 3 to DEC by Division Example:

Given Base 3 = 202
2 * 3^2 + 0 * 3^1 + 2 * 3^0 = 18 + 0 + 2 = 20

Binary (base 3)number * baseN ^ bit positionResult (sum all together)
22 * 3^02
00 * 3^10
22 * 3^218
DEC = 18 + 0 + 2 = 20

Convert OCT to DEC by Division Example:

Given OCT = 024 = 2 x 8^1 + 4 x 8^0

Binary (base 8)number * baseN ^ bit positionResult (sum all together)
44 * 8^04
22 * 8^116
DEC = 16 + 4 = 20

Convert HEX to DEC by Division Example:

Given HEX = 0x14

Binary (base 16)number * baseN ^ bit positionResult (sum all together)
44 * 16^04
11 * 16^116
DEC = 16 + 4 = 20

Note In C/C++:
DEC is represent : 1234567890 (normal)
OCT is represent : 012345670 (with a zero at the front)
HEX is represent : 0x12345678, 0x9ABCDEF1 (with a”0x”)