Skip to content

Instantly share code, notes, and snippets.

@GenesisFR
Created November 23, 2018 13:20
Show Gist options
  • Save GenesisFR/44c52fa36cd93ec12ac2b5c3e7a74f67 to your computer and use it in GitHub Desktop.
Save GenesisFR/44c52fa36cd93ec12ac2b5c3e7a74f67 to your computer and use it in GitHub Desktop.
C function to convert an integer to a binary string
#include <stdio.h>
#include <stdlib.h>
char * toBinary(int n)
{
const int size = sizeof(n) * 8;
char * str = (char*)malloc(sizeof(char) * (size + 1));
if (str)
{
for (int i = size - 1; i >= 0; i--)
{
str[i] = n % 2 + '0';
n /= 2;
}
str[size] = '\0';
}
return str;
}
int main()
{
int x = 16;
char * s = toBinary(x);
printf(s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment