How to convert between number systems

C++C++Beginner
Practice Now

Introduction

This comprehensive tutorial explores number system conversions using C++, providing developers with essential skills for handling different numerical representations. By understanding conversion methods and implementing practical techniques, programmers can effectively manipulate and transform numbers across various number systems with precision and efficiency.

Number Systems Basics

Introduction to Number Systems

Number systems are fundamental ways of representing numerical values using different bases. In computer science and programming, understanding various number systems is crucial for efficient data manipulation and representation.

Common Number Systems

Number System Base Digits Used Example
Decimal 10 0-9 42
Binary 2 0-1 101010
Octal 8 0-7 52
Hexadecimal 16 0-9, A-F 2A

Decimal Number System (Base 10)

The decimal number system is the most commonly used number system in everyday life. It uses ten digits (0-9) to represent numbers. Each digit's position represents a power of 10.

Example:

Number: 3742
= 3 * 10³ + 7 * 10² + 4 * 10¹ + 2 * 10⁰
= 3000 + 700 + 40 + 2
= 3742

Binary Number System (Base 2)

Binary is the foundation of digital computing. It uses only two digits: 0 and 1.

graph TD A[Decimal] --> B[Binary Conversion] B --> C{Repeated Division by 2} C --> D[Read Remainders Bottom-Up]

Example conversion from decimal to binary:

Decimal 42 to Binary:
42 ÷ 2 = 21 remainder 0
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

Binary: 101010

Hexadecimal Number System (Base 16)

Hexadecimal is widely used in computing because it provides a more compact representation of binary data.

Key characteristics:

  • Uses digits 0-9 and letters A-F
  • Each hex digit represents 4 binary digits
  • Commonly used in memory addresses, color codes, etc.

Importance in Programming

Understanding number systems is essential for:

  • Low-level memory manipulation
  • Bitwise operations
  • Color representation
  • Network addressing
  • Cryptography and encoding

Practical Considerations

When working with different number systems in C++, developers should be aware of:

  • Conversion methods
  • Representation techniques
  • System-specific limitations
  • Performance implications

Note: LabEx provides excellent resources for practicing number system conversions and understanding their practical applications in programming.

Conversion Methods

Overview of Number System Conversion Techniques

Number system conversion is a fundamental skill in programming, involving transforming numbers between different bases systematically and accurately.

Conversion Strategies

1. Decimal to Other Bases Conversion

graph TD A[Decimal Number] --> B[Repeated Division Method] B --> C[Collect Remainders] C --> D[Reverse Remainders]
Decimal to Binary Conversion
  • Divide the decimal number by 2 repeatedly
  • Collect remainders from bottom to top
  • Remainders form the binary representation

Example:

int decimalToBinary(int decimal) {
    int binary = 0, remainder, factor = 1;
    while (decimal > 0) {
        remainder = decimal % 2;
        binary += remainder * factor;
        decimal /= 2;
        factor *= 10;
    }
    return binary;
}

2. Binary to Decimal Conversion

Position Binary Digit Weight Contribution
0 1 2^0 1
1 0 2^1 0
2 1 2^2 4

Example:

int binaryToDecimal(long long binary) {
    int decimal = 0, base = 1;
    while (binary > 0) {
        int lastDigit = binary % 10;
        binary /= 10;
        decimal += lastDigit * base;
        base *= 2;
    }
    return decimal;
}

3. Hexadecimal Conversion Methods

Decimal to Hexadecimal
string decimalToHex(int decimal) {
    string hexChars = "0123456789ABCDEF";
    string hexResult;

    while (decimal > 0) {
        hexResult = hexChars[decimal % 16] + hexResult;
        decimal /= 16;
    }

    return hexResult.empty() ? "0" : hexResult;
}
Hexadecimal to Decimal
int hexToDecimal(string hex) {
    int decimal = 0, power = 0;

    for (int i = hex.length() - 1; i >= 0; i--) {
        char c = toupper(hex[i]);
        int value = (c >= '0' && c <= '9') ?
                    (c - '0') : (c - 'A' + 10);

        decimal += value * pow(16, power++);
    }

    return decimal;
}

Advanced Conversion Techniques

Handling Fractional Numbers

  • Use multiplication method for fractional parts
  • Separate integer and fractional conversions
  • Limit precision to avoid floating-point errors

Performance Considerations

Conversion Type Time Complexity Space Complexity
Decimal → Binary O(log n) O(1)
Binary → Decimal O(log n) O(1)
Decimal → Hex O(log n) O(1)

Best Practices

  1. Use built-in language functions when possible
  2. Handle edge cases (zero, negative numbers)
  3. Validate input before conversion
  4. Consider precision requirements

Note: LabEx recommends practicing these conversion methods to build strong programming fundamentals.

C++ Implementation

Standard Library Conversion Methods

1. Using Standard Conversion Functions

#include <iostream>
#include <string>
#include <bitset>

class NumberConverter {
public:
    // Decimal to Binary
    static std::string decimalToBinary(int decimal) {
        return std::bitset<32>(decimal).to_string();
    }

    // Binary to Decimal
    static int binaryToDecimal(const std::string& binary) {
        return std::stoi(binary, nullptr, 2);
    }

    // Hexadecimal Conversions
    static int hexToDecimal(const std::string& hex) {
        return std::stoi(hex, nullptr, 16);
    }

    static std::string decimalToHex(int decimal) {
        char buffer[20];
        sprintf(buffer, "%X", decimal);
        return std::string(buffer);
    }
};

Custom Conversion Class

Comprehensive Number System Converter

class AdvancedNumberConverter {
private:
    // Utility method for digit to value conversion
    static int charToValue(char c) {
        if (c >= '0' && c <= '9') return c - '0';
        if (c >= 'A' && c <= 'F') return c - 'A' + 10;
        if (c >= 'a' && c <= 'f') return c - 'a' + 10;
        throw std::invalid_argument("Invalid digit");
    }

public:
    // Generic base conversion method
    static int toDecimal(const std::string& number, int base) {
        int decimal = 0;
        int power = 0;

        for (int i = number.length() - 1; i >= 0; --i) {
            decimal += charToValue(number[i]) * std::pow(base, power++);
        }

        return decimal;
    }

    // Decimal to any base conversion
    static std::string fromDecimal(int decimal, int base) {
        if (decimal == 0) return "0";

        const std::string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        std::string result;

        while (decimal > 0) {
            result = digits[decimal % base] + result;
            decimal /= base;
        }

        return result;
    }
};

Practical Implementation Example

int main() {
    // Conversion demonstrations
    try {
        // Standard conversions
        std::cout << "Decimal to Binary: "
                  << NumberConverter::decimalToBinary(42) << std::endl;

        // Advanced conversions
        std::cout << "Binary to Decimal: "
                  << AdvancedNumberConverter::toDecimal("101010", 2) << std::endl;

        // Hex conversions
        std::cout << "Hex to Decimal: "
                  << AdvancedNumberConverter::toDecimal("2A", 16) << std::endl;

        // Decimal to different bases
        std::cout << "Decimal 42 in Base 3: "
                  << AdvancedNumberConverter::fromDecimal(42, 3) << std::endl;
    }
    catch (const std::exception& e) {
        std::cerr << "Conversion error: " << e.what() << std::endl;
    }

    return 0;
}

Conversion Method Complexity

Conversion Type Time Complexity Space Complexity
Decimal to Base O(log n) O(log n)
Base to Decimal O(k) O(1)

Error Handling Strategies

graph TD A[Input Validation] --> B{Valid Input?} B -->|Yes| C[Perform Conversion] B -->|No| D[Throw Exception] C --> E[Return Converted Value] D --> F[Handle Error Gracefully]

Best Practices

  1. Use built-in type conversion methods when possible
  2. Implement robust error handling
  3. Consider performance for large number conversions
  4. Validate input before conversion

Compilation and Execution

To compile on Ubuntu 22.04:

g++ -std=c++11 number_converter.cpp -o number_converter
./number_converter

Note: LabEx recommends practicing these implementation techniques to master number system conversions in C++.

Summary

Through this tutorial, we've demonstrated the fundamental techniques of number system conversions in C++, covering essential conversion methods, implementation strategies, and practical code examples. By mastering these techniques, developers can enhance their programming skills and create more flexible and robust numerical manipulation solutions.