I am writing a program that converts any integer into binary. I have provided a working program that outputs the values of an array that stores the necessary ones or zeroes. The problem arises when I want to convert this array into a single entity so I can just say "cout << entity << endl;" instead of saying "cout << array[?] << endl;" in a loop. Also, how efficient is my algorithm and how can it be improved?
Thanks!
Being new at programming, I am intrigued by your method and would like to know how it works. On a different note, what makes it more efficient? I tested the time it took for each algorithm to print out the binary equivalents of 0 to 1023 and my algorithm was consistently faster by about 5 seconds. Also, I still need an idea on how I would convert the string of 1's and 0's into a single usable entity.
There are no variable length arrays in C++. You probably have a compiler extension enabled which allows this, but it isn't legal C++.
As for the speed, the time spent on the calculation is overwhelmed by the time spent on output, and his version generates quite a bit more output than yours.
#include <iostream>
#include <limits>
#include <string>
usingnamespace std;
string toBinStr(unsignedint val)
{
// mask has only the leftmost bit set.
unsignedint mask = 1u << (std::numeric_limits<unsigned>::digits-1) ;
// skip leading bits that are not set.
while ( 0 == (val & mask) && mask != 0 )
mask >>= 1 ; // shift all bits to the right by 1
string binStr ;
binStr.reserve(std::numeric_limits<unsigned>::digits+1) ;
do
{
// add a '1' or '0' depending the current bit.
binStr += static_cast<char>(val & mask) + '0' ;
} while ( (mask>>=1) != 0 ) ; // next bit, when mask is 0 we've processed all bits
return binStr ;
}
int main()
{
for(unsignedint i = 0; i < 128; i++)
{
string entity = toBinStr(i) ;
cout << entity << '\n' ;
}
}