Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Number base conversion — binary, decimal, hexadecimal

Number base conversion -- binary, decimal, hexadecimal

In this lesson you will master how to convert among the three number bases and understand why hexadecimal is the "best shorthand" for binary.


An everyday analogy: multiple counting systems

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

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

Computers use binary, just as one thinks in terms of "switch states".

Hexadecimal, meanwhile, is the engineer's "shorthand notation"—a shorter way to express lengthy binary.

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

For the same piece of data, the binary representation is 4 times as long as the hexadecimal one.

This is why we need to learn number base conversion.


The essence of number bases: expansion by weight

All number bases work on exactly the same principle—the digit in each position is multiplied by a power of the base, and then everything is added up.

Take the number 42 as an example to see how it is understood in the three bases:

Base Radix Available digits indicates Expansion by weight
Decimal 10 0 ~ 9 42 4 x 101 + 2 x 100 = 42
Binary 2 0, 1 101010 1x25+0x24+1x23+0x22+1x21+0x20 = 42
Hexadecimal 16 0~9, A~F 2A 2 x 161 + 10 x 160 = 42

Key rule: the "radix" of a base determines the weight of each position.

The decimal radix is 10: the ones place has weight 100=1, the tens place 101=10, and the hundreds place 102=100.

Binary radix 2, with weights from right to left of 1, 2, 4, 8, 16, 32, 64, 128.

Hexadecimal radix 16, with weights from right to left of 1, 16, 256, 4096.

Once you understand "expansion by weight", all base conversions become simple. There is only one sentence you need to remember: each digit x radix^position number, then sum them up.


Method 1: decimal to binary (divide-by-2 remainder method)

Suppose you want to convert decimal 42 to binary.

The method is very mechanical:

  1. Divide 42 by 2: quotient 21, remainder 0
  2. Divide 21 by 2: quotient 10, remainder 1
  3. Divide 10 by 2: quotient 5, remainder 0
  4. Divide 5 by 2: quotient 2, remainder 1
  5. Divide 2 by 2: quotient 1, remainder 0
  6. Divide 1 by 2: quotient 0, remainder 1
  7. Read the remainders from bottom to top: 101010

42 ÷ 2 =

21

Remainder

0

← (lowest bit)

21 ÷ 2 =

10

Remainder

1

10 ÷ 2 =

5

Remainder

0

5 ÷ 2 =

2

Remainder

1

2 ÷ 2 =

1

Remainder

0

1 ÷ 2 =

0

Remainder

1

← (highest 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 lowest bit), and the quotient is divided by 2 again to get the next bit.

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


Method 2: binary to decimal (expansion by weight)

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

Binary 101010(numbering positions 0~5 from right to left):

Position 5 4 3 2 1 0
Binary bit 1 0 1 0 1 0
Weight (2^n) 32 16 8 4 2 1
Bit x weight 1x32 0x16 1x8 0x4 1x2 0x1

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


Hexadecimal: the "shorthand notation" for binary

The biggest problem with binary is that it is too long to write.

An 8-bit value takes 8 digits to write, and a 32-bit value takes 32 digits.

This is neither convenient for humans to read nor free of errors.

Hexadecimal solves this problem because of an important mathematical coincidence:

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

Mapping table of 4 binary bits to 1 hexadecimal digit

Binary (4 bits) Decimal Hexadecimal Binary (4 bits) Decimal Hexadecimal
0000 0 0 1000 8 8
0001 1 1 1001 9 9
0010 2 2 1010 10 A
0011 3 3 1011 11 B
0100 4 4 1100 12 C
0101 5 5 1101 13 D
0110 6 6 1110 14 E
0111 7 7 1111 15 F

This table is the core of hexadecimal.

Once memorized, any binary-to-hexadecimal conversion is a mechanical "look up the table and pick the character" operation.

Example: converting binary 11111111 to hexadecimal

The 8 binary bits are split into two groups of 4 bits each:

1111

=

F

  

1111

=

F

 → Result:

0xFF

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


Interactive demo: three-column synchronized converter

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

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

Notice the highlighted color blocks below the binary column—they show how a group of 4 bits corresponds to 1 hexadecimal digit.

Decimal

Radix=10, digits=0~9

Binary

Radix=2, digits=0,1

Hex

Radix=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 fall into place.


Code demo: complete base conversion

Example

Complete base conversion tool (runoob demo)

def

decimal_to_binary

(

n

)

:

   

"""Decimal to binary: divide-by-2 remainder method, showing the full 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} 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: expansion by weight"""

   

decimal

=

0

    length

=

len

(

bin_str

)

   

print

(

f

"Binary {bin_str} expanded by weight:"

)

   

for

i

,

ch

in

enumerate

(

bin_str

)

:

        power

=

length -

1

       

if

ch

==

'1'

:

            value

=

2

** power

           

decimal

=

value

           

print

(

f

" Bit{power}: 1 x 2^{power} = {value}"

)

   

print

(

f

" → Total: {decimal}"

)

   

return

decimal

def

bin_to_hex

(

bin_str

)

:

   

"""Binary to hexadecimal: look up the table in groups of 4 bits"""

   

while

len

(

bin_str

)

%

4

!=

0

:

        bin_str

=

'0'

    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}"

)

   

Strip leading zeros (but keep at least one digit)

    result

=

result.

lstrip

(

'0'

)

or

'0'

   

print

(

f

"  → {result}"

)

   

return

result

Comprehensive test: centered on the ASCII code 82 of the RUNOOB character 'R'

print

(

"="

50

)

print

(

"Test value: 82 (ASCII 'R' from RUNOOB)"

)

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 one byte)"

)

print

(

"="

50

)

bin_255

=

decimal_to_binary

(

255

)

print

(

f

"Binary: {bin_255}"

)

hex_255

=

bin_to_hex

(

bin_255

)

print

(

f

"Hexadecimal: 0x{hex_255}"

)

print

(

"Note: the binary of 255 is 8 all-1 bits, while hexadecimal uses only 2 digits FF"

)


Advanced: fast conversion from hexadecimal to decimal

You already know two ways to convert to decimal: one is expansion by weight (each hexadecimal digit x a power of 16), the other is to convert to binary first and then to decimal.

But there is an even 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 is computationally heavier, while conversion of each with binary is very simple.

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

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