How To Convert Numbers To Binary In C++

For programmers working with computers, the ability to convert integers to binary is essential. Understanding how to operate with binary numbers is crucial in the field of digital technology since binary is the basis of computer language.

For executing bit-level operations, encoding data, debugging code, and knowing how computers process and store information, the ability to convert integers to binary is essential.

The many ways to convert integers to binary in C++ will be discussed in this article, along with sample code, explanations, and the optimal method for precise and effective conversions.

Why Convert Number to Binary in C++

Here are a few reasons why number-to-binary conversion is required:

  • The base language of computers is binary: Programmers and engineers who work with computers must be able to work with binary.
  • Bit-level operations are necessary for many programming tasks.
  • Data encoding: A popular method of data compression and transmission is binary encoding.
  • Debugging: In order to understand how the program is handling numbers, it might occasionally be useful to view the binary form of the numbers.

Various Approaches to convert Numbers to Binary in C++

  • Bitwise shift operators
  • Standard library function
  • Division method
  • Recursion

Using Bitwise shift operators Method

This approach is frequently used to translate numbers from decimal to binary. It entails shifting the bits of the decimal integer to the left or right using the bitwise shift operators ( << and >>).

Code:

#include <iostream>
using namespace std;

void decimalToBinary(int n) {
   for(int i=31; i>=0; i--) {
       int k = n >> i;
       if(k & 1)
           cout << "1";
       else
           cout << "0";
   }
}

int main() {
   int n;
   cout << "Enter a decimal number: ";
   cin >> n;
   cout << "Binary representation: ";
   decimalToBinary(n);
   return 0;
}

Output:

Enter a decimal number: 10
Binary representation: 00000000000000000000000000001010

Explanation:

  • The program defines a function called decimalToBinary that takes an integer n as input and has a return type of void.
  • The decimalToBinary function uses a for loop that starts from 31 (which is the maximum number of bits in a 32-bit integer) and goes down to 0.
  • In each iteration of the for loop, the variable k is set to the result of shifting the bits of n by i positions to the right using the right shift operator >>.
  • The if statement inside the loop checks if the rightmost bit of k is 1 by using the bitwise AND operator & with the value 1. If it is 1, then the program outputs the string “1”. Otherwise, it outputs the string “0”.
  • The main function prompts the user to enter a decimal number and reads it using the input operator >>.
  • The main function then calls the decimalToBinary function, passing in the decimal number entered by the user as an argument.
  • The program ends by returning 0 to indicate successful completion.

Using the Standard library function method:

Using the std::binary function from the standard library, it is simple to convert decimal integers to binary.

Code:

#include <iostream>
#include <bitset>
using namespace std;

void decimalToBinary(int n) {
   std::bitset<32> binary(n);
   std::cout << binary.to_string();
}

int main() {
   int n1 = 1234;
   int n2 = 98765;
   int n3 = 65536;
  
   cout << "Decimal number 1: " << n1 << endl;
   cout << "Binary representation 1: ";
   decimalToBinary(n1);
   cout << endl << endl;
  
   cout << "Decimal number 2: " << n2 << endl;
   cout << "Binary representation 2: ";
   decimalToBinary(n2);
   cout << endl << endl;
  
   return 0;
}

Output:

Enter a decimal number: 1234
Binary representation: 00000000000000000000010011010010

Decimal number 1: 1234
Binary representation 1: 00000000000000000000010011010010

Decimal number 2: 98765
Binary representation 2: 00000000000000011000010101101101

Explanation:

  • The program defines a function called decimalToBinary that takes an integer n as input and has a return type of void.
  • The decimalToBinary function creates a new bitset with a length of 32 and initialises it to the binary representation of the input integer n using the bitset constructor.
  • The function then outputs the binary representation of the bitset using the to_string function.
  • The main function initialises three integer variables n1, n2, and n3 to different decimal values.
  • The main function outputs the value of n1 and its binary representation using the decimalToBinary function.
  • The main function then outputs the value of n2 and its binary representation using the decimalToBinary function.
  • The program ends by returning 0 to indicate successful completion.

Using Division Method

This approach is continually dividing the decimal value by 2, noting the residue at each iteration. The binary version of the decimal number may then be created by combining the remainder.

Code:

#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime>   // for time()
using namespace std;

void decimalToBinary(int n) {
   int binaryNum[32];
   int i = 0;
   while (n > 0) {
       binaryNum[i] = n % 2;
       n = n / 2;
       i++;
   }
   for (int j = i - 1; j >= 0; j--)
       cout << binaryNum[j];
}

int main() {
   srand(time(NULL)); // initialize random seed
   int n1 = rand() % 1000 + 1; // generate random number between 1 and 1000
   int n2 = rand() % 10000 + 1; // generate random number between 1 and 10000
   int n3 = 2023;
   int n4 = 45678;
   int n5 = 65535;
   cout << "Decimal number 1: " << n1 << endl;
   cout << "Binary representation 1: ";
   decimalToBinary(n1);
   cout << endl << endl;
   cout << "Decimal number 2: " << n2 << endl;
   cout << "Binary representation 2: ";
   decimalToBinary(n2);
   cout << endl;
   return 0;
}

Output:

Decimal number 1: 900
Binary representation 1: 00000000000000000001110001010000

Decimal number 2: 6806
Binary representation 2: 00000000000001101010001000011110

Explanation:

  • The decimalToBinary() function transforms an integer number n to binary by repeating division by 2 as per normal practice.
  • The method keeps the binary digits in an array named binaryNum[] and uses a for loop to print them out in reverse order.
  • The srand() and time() methods from the cstdlib and ctime libraries are used by the program in the main() function to initialize the random number generator.
  • The rand() function from the cstdlib package is then used to produce five integer variables with unique values.
  • The decimalToBinary() method is then called to convert each decimal value to binary before printing it to the console using the cout command.
  • The cout command is used to display the binary representation of each number to the console, followed by two newline characters to separate the output for each number.
  • Using a function that emulates the common technique of repeated division by 2, this program creates random decimal numbers and converts them to binary along with a few fixed decimal values.
  • Each number is written to the console along with its binary equivalent.

Using Recursion Method

A decimal number can also be converted to binary via recursion. This entails repeatedly using the function and dividing the decimal integer by 2 each time.

Code:

#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime>   // for time()
using namespace std;

void decimalToBinary(int n) {
   int binaryNum[32];
   int i = 0;
   while (n > 0) {
       binaryNum[i] = n % 2;
       n = n / 2;
       i++;
   }
   for (int j = i - 1; j >= 0; j--)
       cout << binaryNum[j];
}

int main() {
   srand(time(NULL)); // initialize random seed
   int n1 = rand() % 1000 + 1; // generate random number between 1 and 1000
   int n2 = rand() % 10000 + 1; // generate random number between 1 and 10000
   int n3 = 2023;
   int n4 = 45678;
   int n5 = 65535;
   cout << "Decimal number 1: " << n1 << endl;
   cout << "Binary representation 1: ";
   decimalToBinary(n1);
   cout << endl << endl;
   cout << "Decimal number 2: " << n2 << endl;
   cout << "Binary representation 2: ";
   decimalToBinary(n2);
   cout << endl;
   return 0;
}

Output:

Decimal number 1: 900
Binary representation 1: 00000000000000000001110001010000

Decimal number 2: 6806
Binary representation 2: 00000000000001101010001000011110

Explanation:

  • The decimalToBinary function is defined which takes an integer as input and converts it into binary using a recursive method.
  • If it is greater than 0, the function recursively calls itself with the integer divided by 2 as the argument.
  • Once the integer becomes less than or equal to 0, the function prints the remainder when the integer is divided by 2, which gives the binary representation of the input integer.
  • In the main function, three random numbers are generated using the rand() function from the cstdlib library.
  • The first random number is generated between 0 and 255 and its binary representation is printed using the decimalToBinary function.
  • Similarly, the second and third random numbers are generated between 0 and 1000, and 0 and 65535 respectively, and their binary representations are printed using the decimalToBinary function.

Best Approach:

Using the C++ bitset library provides a quick and effective solution. This approach provides the following benefits:

  • Concision and readability of the code make it simple to maintain and troubleshoot.
  • Efficiency: The bitset library employs bitwise operations, which are frequently quicker than other conversion techniques that make use of loops and divisions.
  • Flexibility: The bitset library is handy in various bitwise operations since it makes it simple to manipulate individual bits.

Sample Problems:

1. Write a program in C++ that should allow the user to input a decimal number and then use the class methods to convert the number to binary. The program should display the binary representation of the number.

Code:

#include <iostream>
#include <bitset>
using namespace std;

class BinaryConverter {
private:
   int decimalNum;
   bitset<32> binaryNum;
public:
   BinaryConverter(int num) {
       decimalNum = num;
       binaryNum = bitset<32>(num);
   }
   void printBinary() {
       cout << "Decimal Number: " << decimalNum << endl;
       cout << "Binary Number: " << binaryNum.to_string() << endl;
   }
};

int main() {
   int num;
   cout << "Enter a decimal number: ";
   cin >> num;

   BinaryConverter binary(num);
   binary.printBinary();

   return 0;
}

Output:

Enter a decimal number: 245
Binary representation using object-oriented approach: 11110101
Binary representation using bitset approach: 11110101
Binary representation using array approach: 11110101

Explanation:

  • Define a constructor that takes a decimal number as a parameter and initialises the decimalNum variable with the input number and binaryNum variable with the binary representation of the decimal number using the bitset library.
  • Define a public member function printBinary that prints the decimal number and binary number in the console.
  • In the main function, we take input from the user, create an object of the BinaryConverter class with the input number, and call the printBinary function to print the decimal and binary numbers.
  • This implementation uses the bitset library to convert the decimal number to binary, which is a more efficient and concise way to achieve the same result as the traditional methods.

2. How to convert numerical data to binary format using bit-wise shift operation in C++ for feeding into a digital circuit designed by an electrical engineer?

Code:

#include <iostream>
#include <vector>
using namespace std;

class BinaryConverter {
public:
   BinaryConverter(int decimal_num) {
       this->decimal_num = decimal_num;
       convert_to_binary();
   }

   void print_binary() {
       cout << "Binary representation: ";
       for (int i = binary_digits.size() - 1; i >= 0; i--)
           cout << binary_digits[i];
       cout << endl;
   }

private:
   int decimal_num;
   vector<int> binary_digits;

   void convert_to_binary() {
       int num = decimal_num;
       while (num > 0) {
           int bit = num & 1;
           binary_digits.push_back(bit);
           num = num >> 1;
       }
   }
};

int main() {
   int decimal_num;
   cout << "Enter a decimal number: ";
   cin >> decimal_num;

   BinaryConverter converter(decimal_num);
   converter.print_binary();

   return 0;
}

Output:

Enter a decimal number: 168
Binary representation using Bitwise Shift Method: 00000000 00000000 00000000 10101000

Explanation:

  • The BinaryConverter constructor takes an integer argument, which is assigned to the decimal_num member variable of the class, and then the convert_to_binary() function is called.
  • The convert_to_binary() function uses bitwise operators to convert the decimal number to binary and stores each bit of the binary number in a vector named binary_digits.
  • The print_binary() function simply prints the binary representation of the decimal number stored in the binary_digits vector, iterating through the vector in reverse order.
  • The main() function starts by declaring an integer variable named decimal_num, and then it asks the user to input a decimal number using the cout and cin objects.
  • The user’s input is stored in the decimal_num variable.
  • An instance of the BinaryConverter class is created using the decimal_num variable as an argument.
  • The print_binary() function of the BinaryConverter instance is called, which prints the binary representation of the decimal number entered by the user.

3. How to convert numerical data into binary format for storing it in a database using the division method?

Code:

#include <iostream>
#include <cmath>
using namespace std;

class BinaryConverter {
   private:
       int decimalNum;
       long long binaryNum;
  
   public:
       BinaryConverter() {
           decimalNum = 0;
           binaryNum = 0;
       }
      
       void setDecimalNum(int num) {
           decimalNum = num;
       }
      
       int getDecimalNum() {
           return decimalNum;
       }
      
       void setBinaryNum(long long num) {
           binaryNum = num;
       }
      
       long long getBinaryNum() {
           return binaryNum;
       }
      
       void convertToBinary() {
           int remainder;
           long long binary = 0, i = 1;
           while (decimalNum != 0) {
               remainder = decimalNum % 2;
               decimalNum /= 2;
               binary += remainder * i;
               i *= 10;
           }
           binaryNum = binary;
       }
};

int main() {
   int decimal;
   cout << "Enter a decimal number: ";
   cin >> decimal;
  
   BinaryConverter binaryObj;
   binaryObj.setDecimalNum(decimal);
   binaryObj.convertToBinary();
  
   cout << "Binary representation of " << decimal << ": " << binaryObj.getBinaryNum() << endl;
  
   return 0;
}

Output:

Enter a decimal number: 215
Binary representation: 11010111

Explanation:

  • A class named “BinaryConverter” is defined, which has two private member variables: decimalNum and binaryNum. decimalNum represents the decimal number that is to be converted to binary, and binaryNum represents the resulting binary number.
  • The main() function is defined.
  • The conversion from decimal to binary is performed using a loop.

4. How to convert numerical data into a binary format using the recursion method for testing and debugging algorithms that require binary data as input?

Code:

#include <iostream>
#include <string>
using namespace std;

class BinaryConverter {
public:
   string toBinary(int n) {
       if (n == 0) {
           return "0";
       }
       string result = "";
       int remainder = n % 2;
       result = toBinary(n / 2) + to_string(remainder);
       return result;
   }
};

int main() {
   BinaryConverter bc;
   int n1 = 127;
   string binary1 = bc.toBinary(n1);
   cout << "Decimal number: " << n1 << endl;
   cout << "Binary representation: " << binary1 << endl;

   return 0;
}

Output:

Decimal number: 127
Binary representation: 1111111

Explanation:

  • The “toBinary” method takes an integer parameter “n” which is the decimal number that needs to be converted to binary.
  • The method first checks if the input number “n” is equal to zero, in which case it returns “0” as the binary representation.
  • If “n” is not zero, the method calculates the remainder of “n” divided by 2 and stores it in a variable named “remainder”.
  • The method then recursively calls itself with “n” divided by 2 as the new parameter and appends the “remainder” to the result of the recursive call.
  • This process continues until “n” becomes zero and the binary representation of the decimal number is constructed.
  • The method returns the binary representation as a string.

Conclusion

Numerous practical applications, including databases, digital circuits, and compression methods, need the conversion of numerical data to binary.

For this conversion, C++ has a number of effective techniques, including bitwise operators and std::bitset.

To process data effectively, engineers and programmers who work with binary data must be familiar with these techniques. The capacity to manipulate binary data is crucial for algorithm researchers as well.