Defining a binary number as in Problem 57, write the function
int binToDec(const int bin[])
to convert an eight-bit unsigned binary number to a nonnegative decimal integer. Do not
output the decimal integer in the function. Test your function with interactive input.
#include <iostream>
using namespace std;
int binToDec(const int bin[])
{
int length = 8; // 8-bit binary number
int decimal = 0, base = 1;
for (int i = length - 1; i >= 0; i--) { // start from last
element of array and go to first element
if (bin[i] == 1) // if number is 1 then we have to find its decimal
equivalent otherwise we have to do nothing
decimal += base; // add the base
base = base * 2; // increase the power of base
}
return decimal;
}
// Driver Function
int main()
{
int binary[8];
cout << "Enter 8-bit Unsigned Binary Number : ";
for( int i = 0; i < 8; i++)
cin >> binary[i];
cout << "Equivalent Decimal Value is : " << binToDec(binary);
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.