Answer to Question 27A-8
#include <cstdio>
using namespace std;
//=======================================================
// convertBinaryToInteger
//=======================================================
// convertBinaryToInteger takes a null-terminated string,
// binary, holding a binary number with the high-order
// digit first.
//
// It returns the number represented by binary.
//=======================================================
long convertBinaryToInteger(const char* binary)
{
long result = 0;
for(int k = 0; binary[k] != '\0'; k++)
{
result = 2*result + (binary[k] - '0');
}
return result;
}
int main()
{
char binary[51];
// 1. Get the binary number as a null-terminated string,
// starting with the high-order bit, in array binary.
scanf("%s", binary);
// 2. Convert binary to an integer.
long num = convertBinaryToInteger(binary);
// 3. Show the result.
printf("Conversion of %s\n to decimal yields %ld\n",
binary, num);
return 0;
}