Skip to main content

Number Systems Comparison: Binary, Octal, Decimal, and Hexadecimal

Quick Overview: All Number Systems at a Glance

SystemBaseDigits UsedExampleMain Uses
Binary20, 11101₂ = 13₁₀Computer hardware, logic operations
Octal80-715₈ = 13₁₀File permissions, legacy systems
Decimal100-913₁₀Human interaction, mathematics
Hexadecimal160-9, A-FD₁₆ = 13₁₀Memory addresses, colors, debugging

Why Different Number Systems Exist

Think of number systems like different languages - each one is optimized for specific purposes:

1. Hardware Constraints → Binary

  • Computer circuits have two states: ON (1) or OFF (0)
  • Electronic switches naturally work in binary
  • All computer operations ultimately happen in binary

2. Human Intuition → Decimal

  • We have 10 fingers, so base-10 feels natural
  • Mathematical tradition and education use decimal
  • Easy for calculations and everyday use

3. Efficiency and Compactness → Hexadecimal

  • 1 hex digit = 4 binary digits (perfect grouping)
  • Memory addresses are much shorter in hex
  • Debugging and low-level programming prefer hex

4. Specialized Applications → Octal

  • 1 octal digit = 3 binary digits
  • Perfect for Unix file permissions (3 bits = rwx)
  • Historical use in older computer systems

The Same Number in All Systems

Let's see how the same value looks in each system:

Example: The Number "156"

SystemRepresentationCalculation
Decimal156₁₀1×100 + 5×10 + 6×1 = 156
Binary10011100₂1×128 + 0×64 + 0×32 + 1×16 + 1×8 + 1×4 + 0×2 + 0×1 = 156
Octal234₈2×64 + 3×8 + 4×1 = 156
Hexadecimal9C₁₆9×16 + 12×1 = 156

Key insight: These are all the same number, just written in different notation systems!

Conversion Between Systems: Master Reference

Direct Conversion Table (0-20)

DecimalBinaryOctalHexCommon Usage
0000Zero/null values
1111Basic counting
21022Powers of 2
4100444-bit boundary
81000108Byte boundary
10101012ADecimal base
15111117F4-bit maximum
16100002010Hex base
25511111111377FFByte maximum

Binary ↔ Octal Conversion

Key: 1 octal digit = 3 binary digits

Binary to Octal:
Group binary into 3s from right, convert each group

Example: 101110011₂
Step 1: 101 110 011
Step 2: 5 6 3
Result: 563₈

Octal to Binary:
Convert each octal digit to 3 binary digits

Example: 563₈
Step 1: 5→101, 6→110, 3→011
Result: 101110011₂

Binary ↔ Hexadecimal Conversion

Key: 1 hex digit = 4 binary digits

Binary to Hex:
Group binary into 4s from right, convert each group

Example: 10011100₂
Step 1: 1001 1100
Step 2: 9 C
Result: 9C₁₆

Hex to Binary:
Convert each hex digit to 4 binary digits

Example: 9C₁₆
Step 1: 9→1001, C→1100
Result: 10011100₂

Any System to Decimal (Easy Method)

Universal formula: Sum of (digit × base^position)

Example 1: 1011₂ to decimal
= 1×2³ + 0×2² + 1×2¹ + 1×2⁰
= 8 + 0 + 2 + 1 = 11₁₀

Example 2: 2F₁₆ to decimal
= 2×16¹ + F×16⁰
= 2×16 + 15×1 = 47₁₀

Example 3: 37₈ to decimal
= 3×8¹ + 7×8⁰
= 24 + 7 = 31₁₀

Decimal to Any System (Division Method)

Universal method: Divide by target base, collect remainders

Example: Convert 156₁₀ to binary (base 2)
156 ÷ 2 = 78 remainder 0
78 ÷ 2 = 39 remainder 0
39 ÷ 2 = 19 remainder 1
19 ÷ 2 = 9 remainder 1
9 ÷ 2 = 4 remainder 1
4 ÷ 2 = 2 remainder 0
2 ÷ 2 = 1 remainder 0
1 ÷ 2 = 0 remainder 1

Read from bottom up: 10011100₂

Same method works for any base:
- Base 8: divide by 8
- Base 16: divide by 16

Real-World Applications: When to Use Each System

Binary (Base-2): Computer Internals

When computers use binary:

- CPU instructions and data processing
- Memory storage (RAM, hard drives)
- Network communication (packets)
- Digital circuits and logic gates
- Bitwise operations in programming

When programmers use binary:

// Bit manipulation
int flag = 0b10110000; // Binary literal
if (flag & 0b00100000) {
printf("Bit 5 is set\n");
}

// Boolean operations
bool result = (a && b) || (!c && d);

Key insight: Everything in computers is ultimately binary, but we rarely work with it directly.

Decimal (Base-10): Human Interface

When we use decimal:

- User input and output
- Mathematical calculations
- Business logic and algorithms
- Database numeric fields
- Financial calculations

Programming examples:

# All human-facing numbers
price = 29.99
quantity = 5
total = price * quantity # 149.95

# Loop counters
for i in range(100): # 0 to 99
process_item(i)

# Mathematical operations
import math
result = math.sqrt(144) # 12.0

Octal (Base-8): System Administration

Primary use: Unix/Linux file permissions

# File permission examples
chmod 755 script.sh # rwxr-xr-x
chmod 644 document.txt # rw-r--r--
chmod 700 private/ # rwx------

# Understanding the octal breakdown:
# 755 = 111 101 101 (binary) = rwx r-x r-x
# 644 = 110 100 100 (binary) = rw- r-- r--

Other octal uses:

// Escape sequences in C
printf("Hello\n"); // \n = \012 (octal)
char tab = '\t'; // \t = \011 (octal)

// Legacy assembly code
MOV AX, 0o377 // Octal constant

Hexadecimal (Base-16): Programming and Debugging

Memory addresses:

int *ptr = malloc(sizeof(int));
printf("Address: %p\n", ptr); // Output: 0x7fff5a2c1000

Color codes in web development:

.red {
color: #ff0000;
} /* Pure red */
.blue {
background: #0000ff;
} /* Pure blue */
.gray {
border: #808080;
} /* Medium gray */

Low-level programming:

// Hardware registers
#define GPIO_BASE 0x20200000
#define SPI_CS 0x20204000

// Bit masks
uint32_t mask = 0xFF00FF00;
uint32_t result = data & mask;

Network programming:

# IP address manipulation
ip_int = 0xC0A80101 # 192.168.1.1 in hex
mac_address = "00:1B:44:11:3A:B7" # Hex format

Programming Language Support

JavaScript Number Systems

// Literals
const binary = 0b1101; // 13
const octal = 0o15; // 13
const decimal = 13; // 13
const hex = 0xd; // 13

// Conversions
const num = 13;
console.log(num.toString(2)); // "1101" (binary)
console.log(num.toString(8)); // "15" (octal)
console.log(num.toString(10)); // "13" (decimal)
console.log(num.toString(16)); // "d" (hex)

// Parsing strings
parseInt("1101", 2); // 13 (from binary)
parseInt("15", 8); // 13 (from octal)
parseInt("13", 10); // 13 (from decimal)
parseInt("D", 16); // 13 (from hex)

Python Number Systems

# Literals
binary = 0b1101 # 13
octal = 0o15 # 13
decimal = 13 # 13
hex_num = 0xD # 13

# Built-in conversion functions
num = 13
print(bin(num)) # '0b1101'
print(oct(num)) # '0o15'
print(str(num)) # '13'
print(hex(num)) # '0xd'

# Parsing strings
int("1101", 2) # 13
int("15", 8) # 13
int("13", 10) # 13
int("D", 16) # 13

C/C++ Number Systems

#include <stdio.h>

int main() {
// Literals
int binary = 0b1101; // C23/GCC extension
int octal = 015; // Traditional C
int decimal = 13; // Standard
int hex = 0xD; // Standard

// Output in different bases
printf("Binary: %d\n", binary);
printf("Octal: %o\n", octal);
printf("Decimal: %d\n", decimal);
printf("Hex: %X\n", hex);

return 0;
}

Performance and Efficiency Considerations

Speed Comparison

Fastest to slowest for computer processing:

  1. Binary operations - Direct hardware support

    x & 0xFF;           // Bit masking
    x << 2; // Bit shifting
    x | 0x80; // Bit setting
  2. Hexadecimal parsing - Simple 4-bit grouping

    unsigned int hex_to_int(char c) {
    return (c >= '0' && c <= '9') ? c - '0' : c - 'A' + 10;
    }
  3. Octal parsing - 3-bit grouping

    unsigned int octal_digit(char c) {
    return c - '0'; // Simple subtraction
    }
  4. Decimal conversion - Requires division/multiplication

    // More complex algorithms needed
    int decimal_to_binary(int n) {
    // Requires repeated division
    }

Memory Usage

Storage efficiency for the same value:

Value: 255 (maximum byte value)

Binary: 11111111 (8 characters)
Octal: 377 (3 characters)
Decimal: 255 (3 characters)
Hex: FF (2 characters) ← Most compact!

Why hex is preferred for memory:

  • Most compact representation
  • Direct relationship to binary (4 bits = 1 hex digit)
  • Easy for humans to read and verify
  • Aligns with byte boundaries (2 hex digits = 1 byte)

Common Pitfalls and How to Avoid Them

Pitfall 1: Mixing Number Systems

// ❌ Dangerous: Mixing systems without clarity
let value1 = 012; // Octal 12 = 10 decimal
let value2 = 12; // Decimal 12
let sum = value1 + value2; // 10 + 12 = 22 (unexpected!)

// ✅ Clear: Use explicit notation
let octal = 0o12; // Clearly octal
let decimal = 12; // Clearly decimal
let sum = octal + decimal; // 10 + 12 = 22 (expected)

Pitfall 2: Invalid Digits

# ❌ Wrong: Using invalid digits for the base
try:
int("789", 8) # Error! 8 and 9 don't exist in octal
except ValueError:
print("Invalid octal digit")

# ✅ Correct: Only use valid digits
int("567", 8) # Valid octal
int("ABC", 16) # Valid hex

Pitfall 3: Case Sensitivity Confusion

// Both are correct, but be consistent
int hex1 = 0xabc; // Lowercase
int hex2 = 0xABC; // Uppercase
// hex1 == hex2 (both equal 2748)

// In strings, case matters for readability
printf("0x%X\n", value); // Uppercase output
printf("0x%x\n", value); // Lowercase output

Pitfall 4: Prefix Confusion

# Different prefixes in different contexts
0b1101 # Binary (programming languages)
1101# Binary (mathematical notation)
0o15 # Octal (modern programming)
015 # Octal (traditional C, dangerous!)
0x15 # Hex (universal)
15₁₆ # Hex (mathematical notation)

Advanced Conversion Techniques

Fast Mental Conversion Tricks

Powers of 2 (memorize these):

2⁰ = 1      2⁴ = 16     2⁸ = 256
2¹ = 2 2⁵ = 32 2⁹ = 512
2² = 4 2⁶ = 64 2¹⁰ = 1024
2³ = 8 2⁷ = 128 2¹¹ = 2048

Quick hex-to-decimal:

A = 10    (think: A is the 10th letter starting from 0)
B = 11 (A + 1)
C = 12 (A + 2)
D = 13 (A + 3)
E = 14 (A + 4)
F = 15 (A + 5)

Binary grouping:

For hex: Group by 4 bits
1010 1111 0011 = AF3₁₆

For octal: Group by 3 bits
101 011 110 011 = 5363₈

Programming Implementation

class NumberConverter:
def __init__(self, value, base):
self.decimal = self._to_decimal(value, base)

def _to_decimal(self, value, base):
"""Convert any base to decimal"""
if isinstance(value, str):
return int(value, base)
return value

def to_binary(self):
return bin(self.decimal)[2:] # Remove '0b' prefix

def to_octal(self):
return oct(self.decimal)[2:] # Remove '0o' prefix

def to_hex(self):
return hex(self.decimal)[2:].upper() # Remove '0x', uppercase

def to_decimal(self):
return str(self.decimal)

def display_all(self):
return {
'binary': self.to_binary(),
'octal': self.to_octal(),
'decimal': self.to_decimal(),
'hexadecimal': self.to_hex()
}

# Usage examples
converter = NumberConverter("FF", 16)
print(converter.display_all())
# {'binary': '11111111', 'octal': '377', 'decimal': '255', 'hexadecimal': 'FF'}

converter = NumberConverter("1010", 2)
print(converter.display_all())
# {'binary': '1010', 'octal': '12', 'decimal': '10', 'hexadecimal': 'A'}

Number System Decision Tree

Need to represent a number? Ask yourself:

1. Is this for human interaction?
├─ YES → Use Decimal
└─ NO → Continue to #2

2. Is this for memory addresses or debugging?
├─ YES → Use Hexadecimal
└─ NO → Continue to #3

3. Is this for file permissions or legacy systems?
├─ YES → Use Octal
└─ NO → Continue to #4

4. Is this for bit manipulation or hardware?
├─ YES → Use Binary
└─ NO → Default to Decimal

Quick Reference: Conversion Cheat Sheet

Common Values in All Systems

DecimalBinaryOctalHexSignificance
0000Zero/null
1111Unity
81000108Byte bits
16100002010Hex base
321000004020Common bit boundary
64100000010040Cache line size
1281000000020080Signed byte max
25511111111377FFByte maximum
256100000000400100Next power of 2
51210000000001000200Common buffer size
1024100000000002000400Kilobyte

Programming Quick Conversions

// JavaScript one-liners
const toBinary = (n) => n.toString(2);
const toOctal = (n) => n.toString(8);
const toHex = (n) => n.toString(16).toUpperCase();
const fromBinary = (s) => parseInt(s, 2);
const fromOctal = (s) => parseInt(s, 8);
const fromHex = (s) => parseInt(s, 16);

// Usage
console.log(toBinary(255)); // "11111111"
console.log(toHex(255)); // "FF"
console.log(fromHex("FF")); // 255

Key Takeaways

All number systems represent the same values - just in different notation
Choose the right system for the task: Decimal for humans, hex for memory, octal for permissions, binary for hardware
Learn the conversion patterns: 4 bits = 1 hex, 3 bits = 1 octal
Master the common values: Powers of 2, byte boundaries, and frequently used numbers
Use consistent notation: Proper prefixes (0x, 0o, 0b) prevent confusion
Practice mental conversion: For common values like 255, 1024, etc.

Understanding number systems is fundamental to computer science because:

  • Computers think in binary but we need readable representations
  • Different systems optimize for different use cases
  • Conversion between systems is a daily programming task
  • Debugging often requires understanding hex and binary
  • System administration uses octal for permissions
  • Low-level programming requires bit-level thinking

Mastering number systems makes you a more effective programmer, better at debugging, and gives you deeper insight into how computers actually work at the fundamental level.