summaryrefslogtreecommitdiff
path: root/static/20240817-aarch64-bootstrapping-1/hex.c
blob: aca16e2ad33dbf926cc678f7fec9f4160ea55328 (plain)
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
#include <stdio.h>

int main(void) {
  char c = 0;      // Input character
  int count = 0;   // Hex digits parsed for this number
  long long v = 0; // Current value

  while ((c = getchar()) != EOF) {

    // Skip comments
    if (c == '\\') { while ((c = getchar()) != EOF && c != '\n') {} }

    // Process incoming digits and add to running value
    else if (('0' <= c) && (c <= '9')) { v = (v << 4) + (c - '0'); count++; }
    else if (('a' <= c) && (c <= 'f')) { v = (v << 4) + (c - 'a' + 10); count++; }

    // Send the finished number out the other end
    else if (c == ' ') {

      // Turn the number of hex digits into a number of bytes
      if (count & 1) count++;
      count >>= 1;

      // Emit each byte, littlest first
      for (; count>0; count--) {
        c = v & 0xFF;
        putchar(c);
        v >>= 8;
      }
    }
  }
}