fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct
  6. {
  7. size_t len;
  8. unsigned char* str;
  9. } HexString;
  10.  
  11. int hex_to_int(unsigned char c)
  12. {
  13. int first =0;
  14. int second =0;
  15. int result=0;
  16. if (c >= 97 && c <= 102) /* 97 = 'a'; 102 = 'f' */
  17. c -= 32;
  18. first = c / 16 - 3;
  19. second = c % 16;
  20. result = first * 10 + second;
  21. if (result > 9) result--;
  22. return result;
  23. }
  24.  
  25. unsigned char hex_to_ascii(unsigned char c, unsigned char d)
  26. {
  27. unsigned char a = '0';
  28. int high = hex_to_int(c) * 16;
  29. int low = hex_to_int(d);
  30. a = high + low;
  31. return a;
  32. }
  33.  
  34. HexString HextoString(const char* const st)
  35. {
  36. HexString result;
  37. size_t length = strlen(st);
  38. result.len = length/2+1;
  39. result.str = malloc(length/2+1);
  40. size_t i;
  41. size_t j = 0;
  42. unsigned char buf = 0;
  43. for (i = 0; i < length; i++)
  44. {
  45. if (i % 2 != 0)
  46. {
  47. result.str[j++] = hex_to_ascii(buf, st[i]);
  48. }
  49. else
  50. {
  51. buf = (unsigned char)st[i];
  52. }
  53. }
  54. result.str[length/2+1] = '\0';
  55. return result;
  56. }
  57.  
  58. int main()
  59. {
  60. size_t i;
  61. HexString hexString = HextoString("0a12345600a0020b12");
  62. for (i = 0; i < hexString.len; ++i)
  63. {
  64. printf("<%02x> ", hexString.str[i]);
  65. }
  66.  
  67. free(hexString.str);
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
<0a> <12> <34> <56> <00> <a0> <02> <0b> <12> <00>