Skip to content

Instantly share code, notes, and snippets.

@Hritik14
Created July 23, 2020 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hritik14/ab84c13551448a0a4593a6651a465d22 to your computer and use it in GitHub Desktop.
Save Hritik14/ab84c13551448a0a4593a6651a465d22 to your computer and use it in GitHub Desktop.
decimal to binary, version B. Uses printf's "%x" modifier. Doesn't support floats.
#include<stdio.h>
#include<string.h>
#define HEX_SIZE 7
/*
* converts hex to bin
* bin MUST be able to accomodate hex_size*4 elements
*/
int hex2bin(char* bin, char* hex, size_t hex_size ){
int i;
for(i=0; hex[i] != 0 && i<hex_size; i++)
switch(hex[i]){
case '0':
strcpy(bin+i*4, "0000");
break;
case '1':
strcpy(bin+i*4, "0001");
break;
case '2':
strcpy(bin+i*4, "0010");
break;
case '3':
strcpy(bin+i*4, "0011");
break;
case '4':
strcpy(bin+i*4, "0100");
break;
case '5':
strcpy(bin+i*4, "0101");
break;
case '6':
strcpy(bin+i*4, "0110");
break;
case '7':
strcpy(bin+i*4, "0111");
break;
case '8':
strcpy(bin+i*4, "1000");
break;
case '9':
strcpy(bin+i*4, "1001");
break;
case 'A':
strcpy(bin+i*4, "1010");
break;
case 'B':
strcpy(bin+i*4, "1011");
break;
case 'C':
strcpy(bin+i*4, "1100");
break;
case 'D':
strcpy(bin+i*4, "1101");
break;
case 'E':
strcpy(bin+i*4, "1110");
break;
case 'F':
strcpy(bin+i*4, "1111");
break;
}
bin[i*4] = '\0';
return 0;
}
int main(){
int n;
char opt;
char buf[100];
char hexbuf[HEX_SIZE];
scanf("%d%c", &n, &opt);
if (opt == 'f'){
puts("Cannot convert float");
return -1;
}
snprintf(hexbuf, 7, "%X", n);
hex2bin(buf, hexbuf, HEX_SIZE);
puts(buf);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment