convert long int to binary string c++
To convert a long int
to a binary string in C++, you can follow these steps:
Include the necessary header files:
cpp #include <bitset> #include <string>
These header files are required to use thebitset
class andstring
class.Declare a
long int
variable:cpp long int number = 12345;
This is thelong int
variable that you want to convert to a binary string. Replace12345
with your desired value.Create a
bitset
object:cpp std::bitset<sizeof(number) * 8> binary(number);
Thebitset
class template represents a fixed-size sequence of bits. Here,sizeof(number) * 8
is used to determine the number of bits required to represent thelong int
variable. Thebinary
bitset object is created and initialized with the value ofnumber
.Convert the
bitset
to astring
:cpp std::string binaryString = binary.to_string();
Theto_string
member function of thebitset
class converts thebitset
object to astring
representation. The resultingbinaryString
will contain the binary representation of thelong int
variable.Print or use the binary string:
cpp std::cout << binaryString << std::endl;
You can print the binary string usingstd::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.