fork download
  1. #include <iomanip>
  2. #include <iostream>
  3. #include <limits>
  4. #include <sstream>
  5. #include <string>
  6.  
  7. using value_type = unsigned long long;
  8.  
  9. std::string as_binary(value_type value)
  10. {
  11. std::ostringstream os;
  12.  
  13. if (value == 0) // no bits set
  14. os << value;
  15. else
  16. {
  17. // set mask's left-most bit.
  18. value_type mask =
  19. value_type{1} << (std::numeric_limits<value_type>::digits - 1);
  20.  
  21. while ((mask & value) == 0) // skip leading 0 bits
  22. mask >>= 1; // shift our set bit to the right
  23.  
  24. while (mask)
  25. {
  26. os << ((mask & value) ? 1 : 0);
  27. mask >>= 1;
  28. }
  29. }
  30.  
  31. return os.str();
  32. }
  33.  
  34. int main()
  35. {
  36. for (value_type i = 0; i < 33; ++i)
  37. {
  38. std::cout << std::setw(2) << i;
  39. std::cout << " = ";
  40. std::cout << std::setw(6) << as_binary(i) << '\n';
  41. }
  42. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
 0 =      0
 1 =      1
 2 =     10
 3 =     11
 4 =    100
 5 =    101
 6 =    110
 7 =    111
 8 =   1000
 9 =   1001
10 =   1010
11 =   1011
12 =   1100
13 =   1101
14 =   1110
15 =   1111
16 =  10000
17 =  10001
18 =  10010
19 =  10011
20 =  10100
21 =  10101
22 =  10110
23 =  10111
24 =  11000
25 =  11001
26 =  11010
27 =  11011
28 =  11100
29 =  11101
30 =  11110
31 =  11111
32 = 100000