Last active
December 17, 2015 05:39
-
-
Save eienf/5559361 to your computer and use it in GitHub Desktop.
decimal to binary
This file contains hidden or 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> | |
#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