Skip to content

Instantly share code, notes, and snippets.

@eienf
Last active December 17, 2015 05:39
Show Gist options
  • Save eienf/5559361 to your computer and use it in GitHub Desktop.
Save eienf/5559361 to your computer and use it in GitHub Desktop.
decimal to binary
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int digit(unsigned long n)
{
if ( n == 0 ) return 1;
int k = (int)(log2(n));
return k+1;
}
int main(int argc,char *argv[])
{
if ( argc < 2 ) {
fprintf(stderr,"Usage : %s number\n",argv[0]);
return -1;
}
unsigned long decimal = atol(argv[1]);
printf("dec = %ld\n",decimal);
int d = digit(decimal);
int length = d + (d/4);
printf("digit = %d\n",d);
char *binary = malloc(length+1);
binary[length] = 0;
for ( int i = 0, s = 0; i < d; i++ ) {
binary[length-i-1-s] = '0' + (decimal>>(i))%2;
if ( (i+1)%4 == 0 ) {
binary[length-i-1-(++s)] = ' ';
}
}
printf("binary = %s\n",binary);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment