This post will discuss how to convert a decimal to binary in C++.

1. Using std::bitset function

The standard solution to convert a number to its binary format in C++ is using the std::bitset class from the <bitset> header. This class represents a fixed-size sequence of bits, which can be manipulated as a single unit or as individual bits. The bitset class is very useful and convenient, as it provides various methods and features for working with bits and binary numbers.

To use the bitset class to convert a decimal to binary, we need to create a bitset object and initialize it with the decimal value that we want to convert. We can also specify the size of the bitset, which determines how many bits are used to represent the value. We can invoke the to_string function to get a std::string representing the bits in the bitset, with leading-zeros. For example, if we want to convert the decimal value 65 to the binary string "01000001", we can do something like this:

Download  Run Code

2. Using custom routine

Another way to convert a decimal to binary in C++ is to use the bitwise operators. The bitwise operators are operators that perform operations on the individual bits of a value, such as shifting, masking, or toggling them. To use the bitwise operators to convert a decimal to binary, we need to perform the following steps:

  1. Create a variable that will store the binary result as a string.
  2. Create a loop that will iterate over each bit of the decimal value from right to left.
  3. In each iteration, use the bitwise AND operator (&) to extract the rightmost bit of the decimal value.
  4. Use the conditional operator (?:) to append either '0' or '1' to the binary result string based on the extracted bit.
  5. Use the right shift operator (>>) to move the decimal value one bit to the right.
  6. Repeat until the decimal value becomes zero.

For example, if we want to convert the decimal value 65 to the binary value "1000001", we can do something like this:

Download  Run Code

 
Note that the above solution does not pad the binary string with leading-zeros. We can even write a recursive custom routine that takes an unsigned integer and print its binary digits. The solution can be implemented as follows in C++:

Download  Run Code

That’s all about converting a decimal to binary in C++.