Skip to content

Instantly share code, notes, and snippets.

@DivinityArcane
Last active August 29, 2015 14:07
Show Gist options
  • Save DivinityArcane/73cea08f18c7273ce171 to your computer and use it in GitHub Desktop.
Save DivinityArcane/73cea08f18c7273ce171 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char byte;
typedef char* string;
string dec2bin(byte x)
{
int i;
string bin = (string)malloc(sizeof(char)*9);
bin[8] = '\0';
for (i = 7; i >= 0; i--) {
bin[7-i] = (x&(1<<i))?'1':'0';
}
return bin;
}
int main (int argc, char** argv) {
byte num;
string bin;
char buf[4];
printf("Enter a number: ");
fgets(buf, 4, stdin);
num = atoi(buf);
bin = dec2bin(num);
printf("The number you entered was: %i\n", num);
printf("Binary: %s\n", bin);
free(bin);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment