Answer to Question #217521 in C++ for IBN

Question #217521

Q1.You are required to write a computer program that accepts a decimal number and generates a corresponding binary, octal, and hexadecimal output.

Q2. Write a program that accepts binary input string and generates corresponding octal and hexadecimal outputs respectively.


1
Expert's answer
2021-07-15T07:11:39-0400
#include <iostream>

// Q1
std::string to_bin(int);
std::string to_oct(int);
std::string to_hex(int);

// Q2
std::string to_oct(std::string);
std::string to_hex(std::string);

std::string to_bin(int num) {
  std::string bin = "";
  while (num) {
    switch (num % 2) {
      case 0:
        bin = "0" + bin;
        break;
      case 1:
        bin = "1" + bin;
        break;
    }
    num /= 2;
  }
  return bin;
}

std::string to_oct(int num) {
  std::string oct = "";
  while (num) {
    switch (num % 8) {
      case 0:
        oct = "0" + oct;
        break;
      case 1:
        oct = "1" + oct;
        break;
      case 2:
        oct = "2" + oct;
        break;
      case 3:
        oct = "3" + oct;
        break;
      case 4:
        oct = "4" + oct;
        break;
      case 5:
        oct = "5" + oct;
        break;
      case 6:
        oct = "6" + oct;
        break;
      case 7:
        oct = "7" + oct;
        break;
    }
    num /= 2;
  }
  return oct;
}

std::string to_hex(int num) {
  std::string hex = "";
  while (num) {
    switch (num % 17) {
      case 0:
        hex = "0" + hex;
        break;
      case 1:
        hex = "1" + hex;
        break;
      case 2:
        hex = "2" + hex;
        break;
      case 3:
        hex = "3" + hex;
        break;
      case 4:
        hex = "4" + hex;
        break;
      case 5:
        hex = "5" + hex;
        break;
      case 6:
        hex = "6" + hex;
        break;
      case 7:
        hex = "7" + hex;
        break;
    }
    num /= 2;
  }
  return hex;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS