Base conversion -- binary, decimal, hexadecimal

In this lecture, you will master the conversion methods between three number systems and understand why hexadecimal is the "best abbreviation" for binary.


Real-life analogy: multiple counting systems

Different number bases are like different "units of measurement."

Humans are accustomed to decimal, just as they are used to measuring height in "meters."

Computers use binary, as if thinking in terms of "switch states."

Hexadecimal, on the other hand, is an engineer's "shorthand" — expressing lengthy binary in a more compact way.

For example: if the word "EXAMPLE" is expressed in three "languages":

  • Decimal: the human language:82 85 78 79 79 66
  • Binary: the machine language:01010010 01010101 01001110 01001111 01001111 01000010
  • Hexadecimal shorthand:52 55 4E 4F 4F 42

The same expression in binary is 4 times as long as in hexadecimal.

This is why we need to learn base conversion.


The essence of bases: expansion by weights

The principles of all bases are exactly the same—Multiply the digit at each position by a power of the base, then add them all together.。

Take the number 42 as an example and see how it is interpreted in each of the three bases:

baseradixAvailable digitsRepresentsWeighted expansion
decimal100 ~ 9424 x 101 + 2 x 100 = 42
binary20, 11010101x25+0x24+1x23+0x22+1x21+0x20 = 42
Hexadecimal160~9, A~F2A2 x 161 + 10 x 160 = 42

Key rule:The 'radix' of a number system determines the weight of each digit。

Decimal has base 10, and the positional weights are powers of 10.0=1, tens place 101=10, hundreds place 102=100。

Binary base 2; the weights from right to left are 1, 2, 4, 8, 16, 32, 64, 128.

Hexadecimal has base 16, and weights from right to left are 1, 16, 256, 4096.

Once you understand "expansion by weights," all base conversions become simple. The only sentence you need to remember is: each digit multiplied by base raised to the position index, then sum them up.


Method 1: Decimal to binary (repeated division by 2, taking remainders)

Suppose you want to convert decimal 42 to binary.

The method is quite mechanical:

  1. Divide 42 by 2; quotient is 21, remainder0
  2. Divide 21 by 2; quotient is 10, remainder1
  3. Divide 10 by 2; quotient is 5, remainder0
  4. Divide 5 by 2, quotient 2, remainder1
  5. Divide 2 by 2, quotient 1, remainder0
  6. Divide 1 by 2, quotient 0, remainder1
  7. Read the remainders from bottom to top:101010
42 ÷ 2 = 21surplus0← (least significant bit)
21 ÷ 2 = 10surplus1
10 ÷ 2 = 5surplus0
5 ÷ 2 = 2surplus1
2 ÷ 2 = 1surplus0
1 ÷ 2 = 0surplus1← (most significant bit)
Result: read the remainders from bottom to top =101010

Why does this method work?

The essence of binary is: N = d0x20 + d1x21 + d2x22 + ...

When N is divided by 2, the remainder is d0(the least significant bit), and the quotient is continuously divided by 2 to get the next bit.

This logic is exactly the same as the "divide by 10 to get the ones digit" you learned in elementary school.


Method 2: Binary to decimal (expansion by weights)

Converting from binary back to decimal is even simpler — just add up the weights directly.

binary101010(Number the positions from right to left as 0 to 5):

Position543210
binary bit101010
Weight (2^n)32168421
bit x weight1x320x161x80x41x20x1

1x32 + 0x16 + 1x8 + 0x4 + 1x2 + 0x1 = 42


Hexadecimal: "shorthand" for binary

The biggest problem with binary isToo long to write out。

An 8-bit value requires writing 8 digits, and a 32-bit value requires 32 digits.

This is inconvenient for humans to read and is prone to errors.

Hexadecimal solves this problem because of an important mathematical coincidence:

24= 16 → every 4 binary bits exactly correspond to 1 hexadecimal digit

Mapping table of 4 binary bits to 1 hexadecimal digit

Binary (4 bits)decimalHexadecimalBinary (4 bits)decimalHexadecimal
000000100088
000111100199
001022101010A
001133101111B
010044110012C
010155110113D
011066111014E
011177111115F

This table is the core of hexadecimal.

Once you memorize it, any binary-to-hexadecimal conversion becomes a mechanical "look up the table and take the digit" operation.

Example: converting binary 11111111 to hexadecimal

8 binary bits are divided into two groups of 4 bits each:

1111 = F    1111 = F→ Result:0xFF

In programming,0xThe prefix denotes hexadecimal (e.g.,0xFF),0bThe prefix denotes binary (e.g.,0b11111111). These prefixes tell the compiler: this is not a decimal number.


Interactive demo: three-column synchronous converter

The converter below lets you observe the correspondence between the three bases in real time.

Enter a value in any column, the other two columns will automatically sync and update.

Pay attention to the highlighted color blocks below the binary column — they show4 bits per group correspond to 1 hexadecimal digitrelationship.

Decimal

Base=10, digits=0~9

Binary

Base=2, digits=0,1

Hexadecimal Hex

Base=16, digits=0~F

Try it: enter 255 in the decimal column, and observe all 1s in the binary column and FF in the hexadecimal column.

This is "the maximum value of one byte" — once you understand this, many concepts become clear.


Code demo: complete base conversion

Example

# Complete base conversion tool (example demo)

def decimal_to_binary(n):
    """Decimal to binary: division by 2 and remainder method, showing complete steps"""
    if n == 0:
        return "0"
    steps = []
    original = n
    while n > 0:
        remainder = n % 2
        quotient = n // 2
        steps.append((n, quotient, remainder))
        n = quotient

    result = ''.join(str(r) for _, _, r in reversed(steps))
    print(f"{original} converted to binary:")
    for val, quot, rem in steps:
        print(f{val:3d} ÷ 2 = {quot:3d} remainder {rem})
    print(f" → Result: {result}")
    return result

def binary_to_decimal(bin_str):
    """Binary to decimal: weighted expansion method"""
    decimal = 0
    length = len(bin_str)
    print(fBinary {bin_str} expanded by weights:)
    for i, ch in enumerate(bin_str):
        power = length - 1 - i
        if ch == '1':
            value = 2 ** power
            decimal += value
            print(fbit {power}: 1 x 2^{power} = {value})
    print(f" → sum: {decimal}")
    return decimal

def bin_to_hex(bin_str):
    """Binary to hexadecimal: look up a table in groups of 4 bits"""
    while len(bin_str) % 4 != 0:
        bin_str = '0' + bin_str
    hex_map = {
        '0000':'0','0001':'1','0010':'2','0011':'3',
        '0100':'4','0101':'5','0110':'6','0111':'7',
        '1000':'8','1001':'9','1010':'A','1011':'B',
        '1100':'C','1101':'D','1110':'E','1111':'F'
    }
    result = ''
    groups = []
    for i in range(0, len(bin_str), 4):
        group = bin_str[i:i+4]
        hex_char = hex_map[group]
        groups.append(f"{group} → {hex_char}")
        result += hex_char
    print(f"Binary {bin_str} to hexadecimal:")
    for g in groups:
        print(f"  {g}")
    print(f"  → 0x{result}")
    return result

def hex_to_bin(hex_str):
    """Hexadecimal to binary: expand each digit into 4 bits"""
    rev_map = {
        '0':'0000','1':'0001','2':'0010','3':'0011',
        '4':'0100','5':'0101','6':'0110','7':'0111',
        '8':'1000','9':'1001','A':'1010','B':'1011',
        'C':'1100','D':'1101','E':'1110','F':'1111'
    }
    hex_str = hex_str.upper()
    result = ''
    for ch in hex_str:
        expanded = rev_map[ch]
        result += expanded
        print(f"  {ch} → {expanded}")
    # Remove leading zeros (but keep at least one digit)
    result = result.lstrip('0') or '0'
    print(f"  → {result}")
    return result

Comprehensive Test: Centered on ASCII code 82 of EXAMPLE character 'R'
print("=" * 50)
print(Test value: 82 (ASCII 'R' from EXAMPLE))
print("=" * 50)
bin_result = decimal_to_binary(82)
print(f"82 → binary: {bin_result}\n")

dec_result = binary_to_decimal(bin_result)
print()

hex_result = bin_to_hex(bin_result)
print()

print("Reverse verification: hexadecimal → binary")
hex_to_bin(hex_result)

print("\n" + "=" * 50)
print(Test value: 255 (maximum value of a byte))
print("=" * 50)
bin_255 = decimal_to_binary(255)
print(fBinary: {bin_255})
hex_255 = bin_to_hex(bin_255)
print(f"Hexadecimal: 0x{hex_255}")
print(Note: The binary representation of 255 is 8 all-1 bits, but the hexadecimal representation uses only 2 digits, FF.)

Advanced: quick conversion from hexadecimal to decimal

You already know two methods for converting to decimal: one is expansion by weights (each hexadecimal digit times a power of 16), and the other is converting to binary first and then to decimal.

But there is a more practical method—Using binary as the 'intermediate language'。

Any base conversion can use binary as a bridge:

decimal ←→ binary ←→ Hexadecimal

Because direct conversion between decimal and hexadecimal involves more computation, but converting each to and from binary is very simple.

Decimal to binary: divide by 2 and take the remainder.

Hexadecimal to binary: expand by looking up the table (each 1 digit becomes 4 bits).

other extensions