Mastering Binary and Decimal Conversions in C++

Prerequisites

To unlock the secrets of binary and decimal conversions, you’ll need a solid grasp of C++ fundamentals, including:

  • functions
  • user-defined function types
  • recursion
  • conditional statements (if, if...else, and nested if...else)
  • while and do...while loops

From Binary to Decimal: Unraveling the Mystery

In this example, we’ll explore a C++ program that converts binary numbers to decimal output.


#include <cmath>

int convert(int binary) {
  int decimal = 0;
  int base = 1;

  while (binary > 0) {
    int rem = binary % 10;
    decimal = decimal + rem * base;
    base = base * 2;
    binary = binary / 10;
  }

  return decimal;
}

int main() {
  int binary;
  std::cout << "Enter a binary number: ";
  std::cin >> binary;
  int decimal = convert(binary);
  std::cout << "The decimal equivalent is: " << decimal << std::endl;
  return 0;
}

Let’s dissect the process using the binary number 1101 as an example. As we iterate through the while loop in the convert() function, we uncover the decimal equivalent: 13.

The Flip Side: Converting Decimal to Binary

Now, let’s flip the script and explore the conversion of decimal numbers to binary.


#include <iostream>

void convert(int decimal) {
  int binaryNum[32];
  int i = 0;

  while (decimal > 0) {
    binaryNum[i] = decimal % 2;
    decimal = decimal / 2;
    i++;
  }

  std::cout << "The binary representation is: ";
  for (int j = i - 1; j >= 0; j--) {
    std::cout << binaryNum[j];
  }
  std::cout << std::endl;
}

int main() {
  int decimal;
  std::cout << "Enter a decimal number: ";
  std::cin >> decimal;
  convert(decimal);
  return 0;
}

Suppose we start with the decimal number 13. As we navigate the while loop in the convert() function, we arrive at the binary representation: 1101.

Exploring Further: Octal Conversions and Beyond

While mastering binary and decimal conversions is a significant achievement, there’s more to explore in the world of C++.

Why not try your hand at:

  • converting binary numbers to octal and vice versa
  • delving into decimal to octal conversions

The possibilities are endless, and with a solid foundation in C++ fundamentals, you’ll be well-equipped to tackle even the most complex programming challenges.

Leave a Reply