Repeatedly asks the user to type in a 4-bit binary value.
Checks the value is exactly 4 digits in length and that it is entirely composed of 0 or 1 symbols before converting it to binary.
Compile on Raspberry Pi, Apple Mac, Linux PC or Windows PC. Alternatively use repl.it
Code below...
// Converting Nibbles - Phil Gardner
#include <iostream>
using namespace std;
// - - - - - - - - - - - - - - - - - - - - - -
bool allDigitsAreBinary( string valueToCheck )
{
bool answer = true;
int index = 0;
while ( answer == true and index < 4 )
{
if ( valueToCheck[index] != '0' && valueToCheck[index] != '1' )
answer = false;
index++;
}
return answer;
}
// - - - - - - - - - - - - - - - - - - - - - - - -
int convertBinaryToDenary( string binaryValue )
{
int total = 0;
int placeValue = 8;
for ( int index = 0; index < 4; index ++ )
{
if ( binaryValue[index] == '1' )
total = total + placeValue;
placeValue = placeValue / 2;
}
return total;
}
// - - - - - - - - - - - - - - - - - - - - - - - -
int main()
{
string nibble;
int len;
// Start of infinite loop
do
{
cout << endl << "Hey you! Type in a binary nibble: ";
cin >> nibble;
// Check we have exactly 4 digits
len = nibble.length();
if ( len == 4 )
{
// Check the digits are only 1 or 0
cout << endl << "Checking nibble is valid... ";
// Attempt the conversion
if ( allDigitsAreBinary( nibble ) )
{
cout << "Nice one." << endl << endl;
cout << "Converting to denary..." << endl;
cout << nibble << " in base 2 is the same as ";
cout << convertBinaryToDenary( nibble ) << " in base 10";
}
else
cout << endl << "Er, hello?! Not *actually* binary...";
}
else
{
cout << endl << "Look, I said type in a nibble. As in *four* bits!" << endl;
cout << "You had to go and ruin it, didn't you?";
} // end of length decision
cout << endl << endl << "- - - - - - - -" << endl << endl;
} while ( true ); // Hey, look! I'm an infinite loop
}