I've just started learning C++ and I've created a simple decimal to binary function and I was wondering if it's okay this way or can it be any quicker or better?
The shortest way to write a function like this I can think of is to use std::bitset
1 2 3 4
std::string decbin( int dec )
{
return std::bitset<sizeof(dec) * CHAR_BIT>(dec).to_string();
}
Problem with this function is that it prints all the leading zeros as well.
I prefer using binary operators for this kind of problem because it is actually bits we are trying to handle.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
std::string decbin( int dec )
{
std::string bits;
do
{
bits += '0' + (dec & 1);
dec >>= 1;
} while (dec);
std::reverse(bits.begin(), bits.end());
return bits;
}
I don't know what you think but to me this is more readable. We don't have to care about maxPow. Only thing I'm not satisfied with is the call to reverse but it has to be there because the string is build in the wrong order.