ic, basic binary to hex using nibbles

This commit is contained in:
2026-06-17 00:35:30 +02:00
parent 6e1a33db8a
commit 450579d266
2 changed files with 64 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
#include <stdio.h>
#include <string.h>
/*
take input
decide if hex or binary
then convert
then print
let's convert binary to hex first
for each byte, split into nibble,
*/
//might have to add some padding, but basic works
void bintohex(char* string_in){
const char hexmap[] = "0123456789ABCDEF";
char hexnum[4];
int stringl = strnlen(string_in, 10)-1;
//aantal nibbles
int loopamount = stringl/4;
printf("totalstringlength=%d\n", stringl);
for (int loopcount = 0; loopcount < loopamount; loopcount++) {
int bin2dec = 0;
//rechts naar links in nibble
for (int nibbledigit = 0 ; nibbledigit <4 ; nibbledigit++) {
//nibblecount + current
int targetdigit = loopcount*4+(4-1-nibbledigit);
//check if j+i = 1
//printf("nibbledigit:%d=%c=%i\n", j, string_in[targetdigit],1<<j);
bin2dec += 1 * (string_in[targetdigit]-'0')*1<<(nibbledigit);
}
hexnum[loopcount]=hexmap[bin2dec];
printf("nibble:%i=%d\n",loopcount,bin2dec);
}
printf("hex=%s", hexnum);
}
int main(){
printf("input either binary or hexadecimal\n");
char buff[32+2]; //4bytes+\n+null
fgets(buff, sizeof(buff), stdin);
bintohex(buff);
}