// @topic W010101 Convert decimal to binary
// @brief Program to convert decimal value to binary representation
// decimal_2_binary.cpp
//
// Known shortcomings:
//
// (1) the algorithm is designed for positive inputs only;
// If negative values need to be processed, then additional
// checks are required.
//
// (2) The number of bits is hardcoded to 8. If the value exceeds
// 255, then program will crash since there are no checks
// against this condition. Perhaps program should change to use an
// array of 32 "bits" instead of 8.
#include <iostream>
int main()
{
unsigned int input = 0;
std::cout << "Enter value: ";
while ( std::cin >> input ) {
// Create a static array of eight "bits"
// and initialize them to zeroes:
int bits[8] = {0};
// A variable to keep track of bit positions:
int pos = 0;
// Populate array of bits with appropriate values:
while( input ) {
// Is number odd or even?
// Modulus operator (remainder of division) gives the answer:
bits[ pos ] = input % 2;
// Divide by two, remainder of the
// division is dropped automatically:
input /= 2;
// Move on to the next position:
++pos;
}
// Display the results, starting with the highest bit:
pos = sizeof( bits ) / sizeof( int ) - 1;
while ( pos >= 0 ) { // Proceed to the lowest bit
std::cout << bits[ pos ]; // display bit value
--pos; // decrement the position.
}
std::cout << "\nEnter value: "; // We are done, repeat the prompt.
}
return 0; // Everything is okay, exiting.
}