fbpx

C++: Binary Digits

Bjarne-stroustrup
 

The task is to output the sequence of binary digits for a given non-negative integer.

The decimal value 5, should produce an output of 101 The decimal value 50 should produce an output of 110010 The decimal value 9000 should produce an output of 10001100101000

The results can be achieved using builtin radix functions within the language, if these are available, or alternatively a user defined function can be used. The output produced should consist just of the binary digits of each number followed by a newline. There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.

#include <bitset>
#include <iostream>
#include <limits>
#include <string>

void print_bin(unsigned int n) {
	std::string str = "0";

	if (n > 0) {
		str = std::bitset<std::numeric_limits<unsigned int>::digits>(n).to_string();
		str = str.substr(str.find('1')); // remove leading zeros
	} 

	std::cout << str << '\n';
}

int main() {
	print_bin(0);
	print_bin(5);
	print_bin(50);
	print_bin(9000);
} 

Output:

0
101
110010
10001100101000

SOURCE

Content is available under GNU Free Documentation License 1.2.