Binary to Octal ) Write a function that returns an octal number from a binary nu
ID: 3888152 • Letter: B
Question
Binary to Octal ) Write a function that returns an octal number from a binary number. The function header is as follows: int bin20ctal (const string& binaryString) Write a test program that prompts the user to enter a binary number as a string and displays the corresponding octal value as a string (Octal to binary) Write a function that returns a binary string from an octal number. The function header is as follows: string octal2Binary(const int& octalNumber) Write a test program that prompts the user to enter an octal number, uses octal2Binary function to parse it into an equivalent binary string and displays the binary stringExplanation / Answer
Source Code:
#include<iostream>
#include <cmath>
#include <string>
using namespace std;
int bin2Octal(const long int binarynum);
string Octal2Binary(int& octalNumber);
int main()
{
long int binnum;
int octalNumber;
cout<<"Enter any binary number : ";
cin>>binnum;
bin2Octal(binnum);
cout << " Enter an octal number: ";
cin >> octalNumber;
Octal2Binary(octalNumber);
return 0;
}
int bin2Octal(const long int binarynum)
{
long int binval,octalnum = 0, j = 1, remainder;
binval=binarynum;
while (binval != 0)
{
remainder = binval % 10;
octalnum = octalnum + remainder * j;
j = j * 2;
binval = binval / 10;
}
cout<<"The Octal equivalent is "<<octalnum;
return 0;
}
string Octal2Binary(int& octalNumber)
{
int decimalNumber = 0, i = 0;
int binaryNumber;
while(octalNumber != 0)
{
decimalNumber += (octalNumber%10) * pow(8,i);
++i;
octalNumber/=10;
}
i = 1;
while (decimalNumber != 0)
{
binaryNumber += (decimalNumber % 2) * i;
decimalNumber /= 2;
i *= 10;
}
cout<<"The binary equivalent is "<<binaryNumber ;
return NULL;
}
Output:
Enter any binary number : 1011
The Octal equivalent is 11
Enter an octal number: 12
The binary equivalent is 1010
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.