March 22, 2024

Understanding Number Systems: Binary, Decimal, and Hexadecimal

8 min readDifficulty: Beginner
Number Systems

Introduction

When working with EVM and smart contracts, you'll frequently encounter different number systems. Understanding how to convert between binary, decimal, and hexadecimal is crucial for working with bytecode, memory addresses, and data representation.

Why Different Number Systems?

Each number system serves a specific purpose:

  • Binary (base-2): Used by computers for internal processing
  • Decimal (base-10): Natural for human counting and calculations
  • Hexadecimal (base-16): Compact representation of binary data

Decimal (Base-10)

The decimal system is what we use in everyday life. It uses 10 digits (0-9) and each position represents a power of 10.

Example: 425₁₀

4 × 10² + 2 × 10¹ + 5 × 10⁰

4 × 100 + 2 × 10 + 5 × 1

400 + 20 + 5 = 425

Binary (Base-2)

Binary uses only two digits (0 and 1). Each position represents a power of 2. In EVM, data is processed at the binary level.

Example: 1101₂

1 × 2³ + 1 × 2² + 0 × 2¹ + 1 × 2⁰

1 × 8 + 1 × 4 + 0 × 2 + 1 × 1

8 + 4 + 0 + 1 = 13₁₀

Hexadecimal (Base-16)

Hexadecimal uses 16 digits (0-9 and A-F). It's commonly used in EVM bytecode and memory addresses because it's a more compact way to represent binary data.

Example: 2A₁₆

2 × 16¹ + 10 × 16⁰

2 × 16 + 10 × 1

32 + 10 = 42₁₀

Quick Conversion Chart

DecimalBinaryHexadecimal
000000
100011
101010A
151111F
161000010

Converting Between Systems

Decimal to Binary

To convert decimal to binary:

  1. Divide the number by 2
  2. Keep track of remainders
  3. Read remainders from bottom to top

Example: 13₁₀ to Binary

13 ÷ 2 = 6 remainder 1 6 ÷ 2 = 3  remainder 0 3 ÷ 2 = 1  remainder 1 1 ÷ 2 = 0  remainder 1 Result: 1101₂

Binary to Hexadecimal

To convert binary to hexadecimal:

  1. Group binary digits into sets of 4
  2. Convert each group to its hex equivalent

Example: 1101 1110₂ to Hex

1101 = D 1110 = E Result: DE₁₆

Common EVM Examples

In EVM, you'll often see numbers represented in hexadecimal with a "0x" prefix. Here are some common examples:

Memory Addresses

0x123f = 4671₁₀

Used for storage slots and memory locations

Bytecode Operations

0x60 = PUSH1

Opcodes are represented in hex

Practice Problems

Try converting these numbers:

1. Convert 42₁₀ to binary and hexadecimal

2. Convert 0xFF to decimal

3. Convert 1100 1010₂ to hexadecimal

Video Resources

Check out this comprehensive video playlist on number systems and conversions:

Tools and Resources

Here are some helpful tools for working with different number systems:

Conclusion

Understanding number systems is fundamental to working with EVM and smart contracts. Practice converting between different bases, and you'll find it becomes more intuitive over time. In our next posts, we'll use this knowledge to better understand EVM bytecode and memory operations.

Comments

Loading comments...

Leave a Comment