fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. typedef unsigned uint;
  6.  
  7. int chhex2val(char ch)
  8. {
  9. if (ch >= '0' && ch <= '9')
  10. return ch - '0';
  11. if (ch >= 'A' && ch <= 'F')
  12. return ch - 'A' + 10;
  13. if (ch >= 'a' && ch <= 'f')
  14. return ch - 'a' + 10;
  15. abort();
  16. return 0;
  17. }
  18.  
  19. char val2chhex(int v)
  20. {
  21. if (v >= 0 && v < 16)
  22. return "0123456789ABCDEF"[v];
  23. abort();
  24. return '0';
  25. }
  26.  
  27. // Multiplies a hex string like "17F" by 10 and
  28. // returns a string with the product (e.g. "0EF6").
  29. // The original string isn't modified.
  30. char* mulh10(char* h)
  31. {
  32. size_t l = strlen(h);
  33. char* p = malloc(l + 1 + 1);
  34. size_t i;
  35. uint c = 0;
  36.  
  37. if (p == NULL)
  38. abort();
  39.  
  40. p[l + 1] = '\0';
  41. for (i = 0; i < l; i++)
  42. {
  43. c += chhex2val(h[l - 1 - i]) * 10;
  44. p[l - i] = val2chhex(c % 16);
  45. c /= 16;
  46. }
  47. p[0] = val2chhex(c);
  48.  
  49. return p;
  50. }
  51.  
  52. // Adds (arithmetically) to a hex string like "17F" a hex/dec digit, e.g. '9'.
  53. // Returns the modified original string (e.g. "188").
  54. char* addhd(char* h, char d)
  55. {
  56. size_t l = strlen(h);
  57. size_t i;
  58. uint c = chhex2val(d);
  59.  
  60. for (i = 0; c && i < l; i++)
  61. {
  62. c += chhex2val(h[l - 1 - i]);
  63. h[l - 1 - i] = val2chhex(c % 16);
  64. c /= 16;
  65. }
  66.  
  67. return h;
  68. }
  69.  
  70. int main(void)
  71. {
  72. char num[] = "17F";
  73. printf("\"17F\" (hex) * 10 = \"%s\" (hex)\n", mulh10(num));
  74. printf("\"17F\" (hex) + '9' = \"%s\" (hex)\n", addhd(num, '9'));
  75. printf("\"65535\" (dec) = \"%s\" (hex)\n",
  76. addhd(mulh10(addhd(mulh10(addhd(mulh10(addhd(mulh10(addhd(mulh10(
  77. "0"), '6')), '5')), '5')), '3')), '5'));
  78. return 0;
  79. }
  80.  
Success #stdin #stdout 0.01s 1808KB
stdin
Standard input is empty
stdout
"17F" (hex) * 10 = "0EF6" (hex)
"17F" (hex) + '9' = "188" (hex)
"65535" (dec) = "00FFFF" (hex)