Created
November 23, 2018 13:20
-
-
Save GenesisFR/44c52fa36cd93ec12ac2b5c3e7a74f67 to your computer and use it in GitHub Desktop.
C function to convert an integer to a binary string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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