#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef unsigned uint;

int chhex2val(char ch)
{
  if (ch >= '0' && ch <= '9')
    return ch - '0';
  if (ch >= 'A' && ch <= 'F')
    return ch - 'A' + 10;
  if (ch >= 'a' && ch <= 'f')
    return ch - 'a' + 10;
  abort();
  return 0;
}

char val2chhex(int v)
{
  if (v >= 0 && v < 16)
    return "0123456789ABCDEF"[v];
  abort();
  return '0';
}

// Multiplies a hex string like "17F" by 10 and
// returns a string with the product (e.g. "0EF6").
// The original string isn't modified.
char* mulh10(char* h)
{
  size_t l = strlen(h);
  char* p = malloc(l + 1 + 1);
  size_t i;
  uint c = 0;

  if (p == NULL)
    abort();

  p[l + 1] = '\0';
  for (i = 0; i < l; i++)
  {
    c += chhex2val(h[l - 1 - i]) * 10;
    p[l - i] = val2chhex(c % 16);
    c /= 16;
  }
  p[0] = val2chhex(c);

  return p;
}

// Adds (arithmetically) to a hex string like "17F" a hex/dec digit, e.g. '9'.
// Returns the modified original string (e.g. "188").
char* addhd(char* h, char d)
{
  size_t l = strlen(h);
  size_t i;
  uint c = chhex2val(d);

  for (i = 0; c && i < l; i++)
  {
    c += chhex2val(h[l - 1 - i]);
    h[l - 1 - i] = val2chhex(c % 16);
    c /= 16;
  }

  return h;
}

int main(void)
{
  char num[] = "17F";
  printf("\"17F\" (hex) * 10 = \"%s\" (hex)\n", mulh10(num));
  printf("\"17F\" (hex) + '9' = \"%s\" (hex)\n", addhd(num, '9'));
  printf("\"65535\" (dec) = \"%s\" (hex)\n",
         addhd(mulh10(addhd(mulh10(addhd(mulh10(addhd(mulh10(addhd(mulh10(
         "0"), '6')), '5')), '5')), '3')), '5'));
  return 0;
}
