language: C99 strict (gcc-4.7.2)
date: 250 days 4 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#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;
}