How To Convert Decimal To Binary In C++

In C++, decimal numbers are typically represented using the float, double, or long double data types. These data types are used to store floating-point numbers, which are real numbers with a fractional component.

In C++, binary numbers can be represented using the binary literal notation 0b. The binary value is represented by a string of binary digits (0 or 1) after the 0b prefix.

The bitwise operators & (bitwise AND), | (bitwise OR), (bitwise XOR), (left shift), and >> can also be used to manipulate binary values (right shift). With the help of these operators, you may carry out bitwise operations on a binary number’s individual bits.

Why we need to convert decimal to binary in c++

In computer programming, converting from decimal to binary is a popular process with a variety of applications. The use of decimal to binary conversion in C++ programming has the following benefits:

  1. Data storage: Decimal numbers must be translated to binary before being stored in memory since computers only store data in binary format.
  2. Bit manipulation: Bitwise operations like AND, OR, XOR, and shift operations can be used to manipulate binary integers.
  3. Networking: In networking, data is often transmitted in binary format, so converting decimal numbers to binary is necessary before sending data over a network.
  4. Cryptography: Cryptographic algorithms often involve binary operations on data, so converting decimal numbers to binary is a common step in cryptographic algorithms.
  5. Optimization: Converting decimal values to binary can be a performance optimization technique since, in some circumstances, binary operations can be faster than decimal operations.

Methods for converting decimal to binary in c++

There are several methods for converting decimal to binary in C++. Here are some commonly used methods:

  1. Division by 2
  2. Bitwise operators
  3. Bitset class
  4. Recursion

Approach 1: Conversion of Decimal to Binary using Division by 2:

This is a straightforward method which involves dividing the number to be converted. To use this technique, divide the decimal number by 2 several times, putting the result (either 0 or 1) in a binary array until the quotient is zero. The binary digits are then read from the array in the reverse manner to produce the decimal number’s binary version.

Code:

#include <iostream>
using namespace std;

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

    int binaryArray[32];
    int index = 0;

    // Convert decimal to binary
    while (decimalNumber > 0) {
        binaryArray[index] = decimalNumber % 2;
        decimalNumber = decimalNumber / 2;
        index++;
    }

    // Print binary representation
    cout << "Binary representation: ";
    for (int i = index - 1; i >= 0; i--) {
        cout << binaryArray[i];
    }
    cout << endl;

    return 0;
}

Output:

Enter a decimal number: 42
Binary representation: 101010

Explanation:

  • The program prompts the user to enter a decimal number.
  • The decimal number is stored in an integer variable called decimalNumber.
  • The program converts the decimal number to binary using a division-based algorithm.
  • The binary digits are stored in an integer array called binaryArray.
  • The binary representation is printed to the screen by iterating through the binaryArray array in reverse order.
  • The program ends after the binary representation is printed.

Approach 2: Conversion of Decimal to Binary using  Bitwise operator

C++ provides several bitwise operators such as left shift (<<) and right shift (>>), which can be used to convert decimal numbers to binary. The bits that arise from shifting the decimal number left or right one bit at a time are saved in a binary array.

Code:

#include <iostream>
using namespace std;

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

    int binaryArray[32];
    int index = 0;

    // Convert decimal to binary using bitwise operators
    while (decimalNumber > 0) {
        binaryArray[index] = decimalNumber & 1;
        decimalNumber = decimalNumber >> 1;
        index++;
    }

    // Print binary representation
    cout << "Binary representation: ";
    for (int i = index - 1; i >= 0; i--) {
        cout << binaryArray[i];
    }
    cout << endl;

    return 0;
}

Output:

Enter a decimal number: 42
Binary representation: 101010

Explanation:

  1. The program prompts the user to enter a decimal number.
  2. The decimal number is stored in an integer variable called decimalNumber.
  3. The program converts the decimal number to binary using bitwise operators.
  4. The binary digits are stored in an integer array called binaryArray.
  5. The binary representation is printed to the screen by iterating through the binaryArray array in reverse order.
  6. The program ends after the binary representation is printed.
  7. Using bitwise operators to convert decimal to binary can be faster than using division.

Approach 3: Conversion of Decimal to Binary using Bitset class

The standard solution to convert a number to its binary format in C++ is using std::bitset. The bitset class provides methods for setting and getting individual bits in a binary representation.

Code:

#include <iostream>
#include <bitset> // Required for the bitset class
using namespace std;

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

    // Convert decimal to binary using bitset class
    bitset<32> binary(decimalNumber);

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

    return 0;
}

Output:

Enter a decimal number: 42
Binary representation: 00000000000000000000000000101010

Explanation:

  1. The program prompts the user to enter a decimal number.
  2. The user enters a decimal number, which is stored in the integer variable decimalNumber.
  3. The program creates a bitset object called binary with a length of 32 and initializes it with the value of decimalNumber. The bitset class provides an easy way to work with binary numbers in C++.
  4. The program then iterates through the binary object in reverse order and prints each binary digit to the screen.
  5. The program outputs a newline character to end the line.

Approach 4: Conversion of Decimal to Binary using Recursion:

We include one base case i.e. when we converge towards zero we have finished our program so we need to exit and a non base case i.e. do mod 2(as it  is binary) and add 10.

Code:

#include <iostream>
using namespace std;

void decimalToBinary(int decimalNumber) {
    if (decimalNumber > 1) {
        decimalToBinary(decimalNumber / 2);
    }
    cout << decimalNumber % 2;
}

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

    // Convert decimal to binary using recursion
    cout << "Binary representation: ";
    decimalToBinary(decimalNumber);
    cout << endl;

    return 0;
}

Output:

Enter a decimal number: 42
Binary representation: 101010

Explanation:

  1. The program prompts the user to enter a decimal number.
  2. The user enters a decimal number, which is stored in the integer variable decimalNumber.
  3. The program calls the decimalToBinary function with the decimalNumber as its argument. This function will convert the decimal number to binary using recursion.
  4. The decimalToBinary function takes an integer argument called decimalNumber.
  5. If decimalNumber is greater than 1, the function calls itself with decimalNumber / 2 as its argument. This means that the function will continue to call itself with smaller and smaller values until decimalNumber is either 0 or 1.
  6. The function then prints out the remainder of decimalNumber when divided by 2, which will be either 0 or 1. This is the binary digit corresponding to the current recursive call.
  7. The program then prints a newline character to end the line.

Best Approach “bitset class” for Conversion of Decimal to Binary:

For various reasons, the bitset class method is regarded as one of the best techniques in C++ for converting from decimal to binary:

  1. Simplicity: The bitset class offers a clear and easy method for converting decimal to binary without the need to create intricate algorithms or loops.
  2. Efficiency: The bitset class is highly optimized for bit manipulation operations and is generally faster than other methods for converting decimal to binary.
  3. Safety: When working with arrays or other low-level data structures, the bitset class’s automatic bounds checking helps prevent buffer overflows and other memory-related issues.
  4. Flexibility: When working with fixed-length binary data, the bitset class’s ability to specify the size of the binary representation can be helpful.
  5. Readability: By offering a high-level abstraction for dealing with binary data, the bitset class improves the readability and comprehension of the code.

Sample Problem:

Sample Problem 1:

Suppose you are working on a project to encrypt sensitive data, such as credit card numbers or personal identification numbers (PINs). In order to encrypt the data, you need to convert the decimal values to binary values and perform bitwise operations on the binary values. Write a program in C++.

Solution:

  1. The code generates 8 random decimal values between 0 and 255.
  2. A 64-bit binary key is created using the bitset class.
  3. Each decimal value is converted to an 8-bit binary value using bitset<8>.
  4. The individual bits of each binary value are copied to the binary key using a nested loop.
  5. The final binary key is printed to the console as a string using the to_string() method of bitset.
  6. The code does not take any input from the user.
  7. The output of the program is the binary key, which is a sequence of 64 bits.

Code:

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

int main() {
    // Generate random decimal values
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(0, 255);
    int decimalValues[8];
    for (int i = 0; i < 8; i++) {
        decimalValues[i] = dis(gen);
    }

    // Convert decimal values to binary using bitset class
    bitset<64> binaryKey;
    int index = 0;
    for (int i = 0; i < 8; i++) {
        bitset<8> binaryValue(decimalValues[i]);
        for (int j = 0; j < 8; j++) {
            binaryKey[index++] = binaryValue[j];
        }
    }

    // Print binary key
    cout << "Binary key: " << binaryKey.to_string() << endl;

    return 0;
}

Output:

Binary key: 0101111000010100001100000000100000011011010001001110110011001101

Sample Problem 2:

In symmetric-key encryption, a secret key is used to encrypt and decrypt data. The key is typically represented as a string of binary digits, which can be generated randomly or derived from a password or passphrase.

In order to securely store or transmit the key, it is often necessary to convert it to a more compact or convenient format, such as a hexadecimal string or a Base64-encoded string. However, before performing the conversion, the key must first be converted from binary to decimal.

Solution:

  1. Generates a random 256-bit key using the rand() function.
  2. Converts the key to a binary string using the bitset class and stores it in the keyBits variable.
  3. Converts the binary string to a hexadecimal string using stringstream, hex, setw, and setfill functions and stores it in the keyHex variable.
  4. Outputs the key in binary and hexadecimal formats using cout.

Code:

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

int main() {
    // Generate random 256-bit key
    unsigned char key[32];
    for (int i = 0; i < 32; i++) {
        key[i] = rand() % 256;
    }

    // Convert key to binary string using bitset class
    bitset<256> keyBits;
    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 8; j++) {
            keyBits.set(i * 8 + j, (key[i] >> (7 - j)) & 1);
        }
    }
    string keyBinary = keyBits.to_string();

    // Convert binary string to hexadecimal string
    stringstream stream;
    for (int i = 0; i < 32; i++) {
        stream << hex << setw(2) << setfill('0') << (int)bitset<8>(keyBinary.substr(i * 8, 8)).to_ulong();
    }
    string keyHex = stream.str();

    // Output key in binary and hexadecimal formats
    cout << "Binary key: " << keyBinary << endl;
    cout << "Hex key: " << keyHex << endl;

    return 0;
}

Output:

Binary key: 0110000001111010110001100001001110100111001100101011110111110001100111100110011111001101111011100010011001000111001100011110001110110111101101101001000110011010100111001110111011011010110111100111000
Hex key: 603AC497EB78CCE39F3BDE3892499CEBB7D6D5A63AECBEE8

Sample Problem 3:

When configuring network devices, it is often necessary to convert IP addresses from their decimal representation to their binary representation. This can be done using the bitset class method, which provides a simple and efficient way to convert each decimal number to an 8-bit binary string and then concatenate the four binary strings to form the 32-bit binary value.

Solution:

  1. The code prompts the user to enter an IP address in decimal format.
  2. The input IP address is stored in a string variable called ipDecimal.
  3. The code initializes an empty string variable called ipBinary to store the binary equivalent of the IP address.
  4. The code uses a loop to iterate through each decimal number in the IP address.
  5. Inside the loop, the decimal number is extracted from the input IP address using the substr() function and converted to binary using the bitset class. The resulting binary string is appended to the ipBinary variable.
  6. The loop continues until all four decimal numbers in the IP address have been converted to binary and appended to ipBinary.
  7. The binary IP address is outputted to the console using cout.

Code:

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

int main() {
    // Input decimal IP address
    string ipDecimal;
    cout << "Enter IP address in decimal format (e.g. 192.168.0.1): ";
    cin >> ipDecimal;

    // Convert IP address to binary using bitset class
    string ipBinary;
    size_t pos = 0;
    for (int i = 0; i < 4; i++) {
        int decimal = stoi(ipDecimal.substr(pos, ipDecimal.find('.', pos) - pos));
        bitset<8> binary(decimal);
        ipBinary += binary.to_string();
        pos = ipDecimal.find('.', pos) + 1;
    }

    // Output binary IP address
    cout << "Binary IP address: " << ipBinary << endl;

    return 0;
}

Output:

Enter IP address in decimal format (e.g. 192.168.0.1): 192.168.0.1
Binary IP address: 11000000101010000000000000000001

Sample Problem 4:

The RSA (Rivest-Shamir-Adleman) algorithm, one of the most widely used encryption algorithms, operates on binary data. The algorithm uses large prime numbers to generate public and private keys, which are used to encrypt and decrypt messages. When encrypting a message, the plaintext is first converted to binary format, then encrypted using the public key. The encrypted binary message is then converted back to decimal format and sent to the recipient.

Solution:

  1. The code prompts the user to enter a decimal number.
  2. The decimal number is read from the standard input stream using cin.
  3. The decimal number is converted to binary using the bitset class with a size of 32 bits, which is enough to represent any 32-bit unsigned integer.
  4. The binary representation is converted to a string using the to_string() method of the bitset class.
  5. The binary representation is output to the console.
  6. The binary representation is converted back to decimal using the to_ulong() function of the bitset class, which returns an unsigned long integer.
  7. The decimal representation is output to the console.

Code:

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

int main() {
    // Input decimal number
    int decimal;
    cout << "Enter decimal number: ";
    cin >> decimal;

    // Convert decimal number to binary using bitset class
    bitset<32> binary(decimal);
    string binaryString = binary.to_string();

    // Output binary number
    cout << "Binary representation: " << binaryString << endl;

    // Convert binary number back to decimal
    int decimalNew = bitset<32>(binaryString).to_ulong();

    // Output decimal number
    cout << "Decimal representation: " << decimalNew << endl;

    return 0;
}

Output:

Enter decimal number: 42
Binary representation: 00000000000000000000000000101010
Decimal representation: 42

Sample Problem 5:

For example, suppose you are working on a project that involves an embedded system controlling a motor. The motor speed is controlled by a user input in the range of 0-100, representing the percentage of maximum speed. The microcontroller needs to convert this decimal input to binary format to control the motor speed.

Solution:

  1. Prompt the user to enter a speed percentage between 0 and 100.
  2. Read the input speed percentage from the user.
  3. Convert the speed percentage to an 8-bit binary representation using the bitset class in C++.
  4. Convert the binary representation to a string.
  5. Output the binary representation to the console.

Code:

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

int main() {
    // Input decimal speed percentage
    int speed;
    cout << "Enter speed percentage (0-100): ";
    cin >> speed;

    // Convert decimal speed percentage to binary using bitset class
    bitset<8> binary(speed);
    string binaryString = binary.to_string();

    // Output binary representation
    cout << "Binary representation: " << binaryString << endl;

    return 0;
}

Output:

Enter speed percentage (0-100): 50
Binary representation: 00110010

Conclusion

In conclusion, understanding the various methods of converting decimal to binary in C++ is essential for any programmer working with binary data. While each method has its advantages and disadvantages, the bitset class method stands out as a reliable and efficient solution.

The bitset class method uses the C++ Standard Template Library (STL) to create a binary representation of a decimal number. It allows us to directly convert a decimal number to its binary equivalent by simply creating a bitset object and initializing it with the decimal value.

Real-life scenarios were also discussed where converting decimal to binary using the bitset class method can be useful, such as in network programming for data transfer, digital image processing, and embedded systems.