I\'m trying to convert an integer 10 into the binary number 1010.
This code attempts it, but I get a segfault on the strcat():
int int_to_bin(int k)
{
The following function converts an integer to binary in a string (n is the number of bits):
// Convert an integer to binary (in a string)
void int2bin(unsigned integer, char* binary, int n=8)
{
for (int i=0;i
Test online on repl.it.
Source : AnsWiki.
The following function converts an integer to binary in a string and allocate memory for the string (n is the number of bits):
// Convert an integer to binary (in a string)
char* int2bin(unsigned integer, int n=8)
{
char* binary = (char*)malloc(n+1);
for (int i=0;i
This option allows you to write something like printf ("%s", int2bin(78));
but be careful, memory allocated for the string must be free later.
Test online on repl.it.
Source : AnsWiki.
The following function converts an integer to binary in another integer (8 bits maximum):
// Convert an integer to binary (in an unsigned)
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
Test online on repl.it
The following function displays the binary conversion
// Convert an integer to binary and display the result
void int2bin(unsigned integer, int n=8)
{
for (int i=0;i
Test online on repl.it.
Source : AnsWiki.