Mastering Number Conversions in C++

Prerequisites for Number Conversions

Before diving into the world of number conversions, it’s essential to have a solid grasp of C++ fundamentals. Make sure you’re familiar with:

  • C++ functions
  • user-defined function types
  • control structures like if-else statements and while loops

Converting Octal to Decimal

When working with octal numbers, converting them to decimal can be a crucial step in your program. Let’s take a closer look at an example that demonstrates this process.


#include <iostream>

int octalToDecimal(int octalNumber) {
  int decimalNumber = 0;
  int base = 1;

  while (octalNumber > 0) {
    int temp = octalNumber % 10;
    decimalNumber += temp * base;
    base *= 8;
    octalNumber /= 10;
  }

  return decimalNumber;
}

int main() {
  int octalNumber = 012; // octal number
  int decimalNumber = octalToDecimal(octalNumber);
  std::cout << "The decimal equivalent of " << octalNumber << " is " << decimalNumber << std::endl;
  return 0;
}

Converting Decimal to Octal

But what about converting decimal numbers to octal? This process is just as important, and we’ll explore it in our next example.


#include <iostream>

std::string decimalToOctal(int decimalNumber) {
  std::string octalNumber = "";
  int temp;

  while (decimalNumber > 0) {
    temp = decimalNumber % 8;
    octalNumber = std::to_string(temp) + octalNumber;
    decimalNumber /= 8;
  }

  return octalNumber;
}

int main() {
  int decimalNumber = 10; // decimal number
  std::string octalNumber = decimalToOctal(decimalNumber);
  std::cout << "The octal equivalent of " << decimalNumber << " is " << octalNumber << std::endl;
  return 0;
}

Exploring Further: Binary Conversions

If you’re interested in exploring more number conversion techniques, be sure to check out our related resources on:

These resources will provide you with a comprehensive understanding of number conversions in C++.

Leave a Reply