Question #6711

# In C, how do you write a function that converts an integer to binary in a string?

The following C function converts an integer to binary and store the result in a string:

``````// Convert an integer to binary
// integer : the integer to convert
// binary : the string containing the conversion result
// n : number of bits (8, 16, 32 ...)
void int2bin(unsigned integer, char* binary, int n=8)
{
for (int i=0;i<n;i++)
binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
binary[n]='\0';
}``````

Try it online on repl.it.

There is another, more user-friendly option which returns the string directly. But be careful, the memory needed for the string is allocated in the function, it is necessary to free it outside the function.

``````// Convert an integer to binary
// integer : the integer to convert
// n : number of bits (8, 16, 32 ...)
// Return a string containing the binary conversion
char* int2bin(unsigned integer, int n=8)
{
char* binary = (char*)malloc(n+1);
for (int i=0;i<n;i++)
binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
binary[n]='\0';
return binary;
}``````

Try it online on repl.it.