Skip to content

Instantly share code, notes, and snippets.

@derekli66
Last active August 29, 2015 14:19
Show Gist options
  • Save derekli66/7d5540d573e227393413 to your computer and use it in GitHub Desktop.
Save derekli66/7d5540d573e227393413 to your computer and use it in GitHub Desktop.
Change decimal numbers into binary format
char *stradd(const char *a, const char *b){
size_t len = strlen(a) + strlen(b);
char *ret = (char *)malloc(len * sizeof(char) + 1);
return strcat(strcat(ret, a), b);
}
char *binaryConverter(int input_number) {
int number = input_number;
char *binaryString = (char *)malloc(sizeof(char));
while (number != 0 ) {
int remainder = number % 2;
number = number/2;
char *remainderChar = (char *)malloc(sizeof(char));
sprintf(remainderChar, "%d", remainder);
binaryString = stradd(remainderChar, binaryString);
free(remainderChar);
}
return binaryString;
}
int main(int argc, const char * argv[]) {
int number = 253;
char *result = binaryConverter(number);
printf("Your binary code: %s", result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment