convert long int to binary string c++

To convert a long int to a binary string in C++, you can follow these steps:

  1. Include the necessary header files: cpp #include <bitset> #include <string> These header files are required to use the bitset class and string class.

  2. Declare a long int variable: cpp long int number = 12345; This is the long int variable that you want to convert to a binary string. Replace 12345 with your desired value.

  3. Create a bitset object: cpp std::bitset<sizeof(number) * 8> binary(number); The bitset class template represents a fixed-size sequence of bits. Here, sizeof(number) * 8 is used to determine the number of bits required to represent the long int variable. The binary bitset object is created and initialized with the value of number.

  4. Convert the bitset to a string: cpp std::string binaryString = binary.to_string(); The to_string member function of the bitset class converts the bitset object to a string representation. The resulting binaryString will contain the binary representation of the long int variable.

  5. Print or use the binary string: cpp std::cout << binaryString << std::endl; You can print the binary string using std::cout or use it for further processing as needed.

Here's the complete code snippet:

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

int main() {
    long int number = 12345;
    std::bitset<sizeof(number) * 8> binary(number);
    std::string binaryString = binary.to_string();
    std::cout << binaryString << std::endl;
    return 0;
}

Make sure to replace 12345 with your desired value.