converter.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <stdio.h>
  2. #include <string.h>
  3. /*
  4. take input
  5. decide if hex or binary
  6. then convert
  7. then print
  8. let's convert binary to hex first
  9. for each byte, split into nibble,
  10. */
  11. //might have to add some padding, but basic works
  12. void bintohex(char* string_in){
  13. const char hexmap[] = "0123456789ABCDEF";
  14. char hexnum[4] = {};
  15. int stringl = strnlen(string_in, 10)-1;
  16. //aantal nibbles
  17. int loopamount = stringl/4;
  18. printf("totalstringlength=%d\n", stringl);
  19. for (int loopcount = 0; loopcount < loopamount; loopcount++) {
  20. int bin2dec = 0;
  21. //rechts naar links in nibble
  22. for (int nibbledigit = 0 ; nibbledigit <4 ; nibbledigit++) {
  23. //nibblecount + current
  24. int targetdigit = loopcount*4+(4-1-nibbledigit);
  25. //check if j+i = 1
  26. //printf("nibbledigit:%d=%c=%i\n", j, string_in[targetdigit],1<<j);
  27. bin2dec += 1 * (string_in[targetdigit]-'0')*1<<(nibbledigit);
  28. }
  29. hexnum[loopcount]=hexmap[bin2dec];
  30. printf("nibble:%i=%d\n",loopcount,bin2dec);
  31. }
  32. printf("hex=%s", hexnum);
  33. }
  34. int main(){
  35. printf("input either binary or hexadecimal\n");
  36. char buff[32+2]; //4bytes+\n+null
  37. fgets(buff, sizeof(buff), stdin);
  38. bintohex(buff);
  39. }