C++ int to binary string conversion program simple example with code documentation. This is custom function implementation example to convert int to binary string in C++. However, we can also useĀ itoa c++ library function for the conversion .
We will consider unsigned long, so, we can convert int to binary string from 0 to 4,294,967,295 number as this is the unsigned long range.
Below is the C++ code to convert int to binary string in C++ with code comments.
C++ int to binary string conversion code
/*--------------------------------------------------
* C++ - Int to Binary String Conversion function
*/
#include <iostream>
using namespace std;
string intToBinaryString( unsigned long n )
{
/*
* Create char array of size = 32+1
* (1 for null terminated string) =33 to
* accommodate 32 byte chars as unsigned long range
* 0 to 4,294,967,295 can be accommodated int to it
*
* Size of unsigned long is 4 bytes, hence for
* 32 byte char array, we need to multiply by 8
*/
char bArray[ (sizeof( unsigned long ) * 8) + 1 ];
//index = 32 to fetch each 32 slots
unsigned index = sizeof( unsigned long ) * 8;
char temp =0;
bArray[ index ] = '\0';
do{
//bArary[ --index ] = '0' + (n & 1);
//Breaking above line to understand better.
temp = (n & 1); // Finding 0 or 1 in LSB
// Adding ASCII 0 to convert Binary to ASCII
temp = temp + '0';
// Copying final ASCII equivalent BIT value (0 or 1)
bArray[ --index ] = temp;
//In while expression :n >>= 1 or equivalent to it is n =n>>1
//can be used. Shifting the Value to RIGHT by one
//to check the NEXT LSB bit.
//Exits when n becomes ZERO.
}while (n >>= 1);
//bArray contains base address. So, jump to
//base address + current index to fetch
//the binary representation.
return string( bArray + index );
}
/*---------------------------------------
* Test - int to binary string C++
*/
int main(){
int n;
cout<<"Enter int number: "<<endl;
cin>> n;
std::string bString = intToBinaryString(n);
cout<<"Binary of "<< n << " is " << bString.c_str()<<endl;
return 0;
}
Output:
Enter int number:
7
Binary of 7 is 111
Enter int number:
24
Binary of 24 is 11000
Enter int number:
512
Binary of 512 is 1000000000