Mike said:
#include <bitset>
#include <climits>
#include <iostream>
#include <string>
unsigned int bin_digits(unsigned int i)
{
unsigned int result(1); /* count 0 as 1 bit */
while(i--)
{
i /= 2;
++result;
}
return result;
}
std::string gen(unsigned int x, unsigned int mx = 5)
{
std::bitset<sizeof x * CHAR_BIT> bs(x);
std::string s(bs.to_string());
return (x <= mx) ? s.substr(s.size() - bin_digits(mx))
: "out of range";
}
int main()
{
for(int i = 0; i < 10; ++i)
std::cout << i << " : " << gen(i) << '\n';
return 0;
}
Seems awfully complicated for such a simple transformation.
#include <string>
#include <iostream>
std::string to_binary(unsigned value)
{
if (5 < value)
return "out of range";
char res[4];
res[3] = '\0';
res[2] = (value & 0x01) ? '1' : '0';
res[1] = (value & 0x02) ? '1' : '0';
res[0] = (value & 0x04) ? '1' : '0';
return res;
}
int main()
{
for(int i = 0; i < 10; ++i)
std::cout << i << " : " << to_binary(i) << '\n';
return 0;
}
Here's one that's even simpler:
char *binary[7] =
{ "000", "001", "010", "011", "100", "101", "out of range" };
std::string to_binary(unsigned value)
{
if (6 < value)
value = 6;
return binary[value];
}
Of course, neither of these honors the artificial constraint that the
code should use STL, if "STL" means "Standard Template Library".