Learn more about Russian war crimes in Ukraine.

A hex compiler in C

Here is a sample of a programming language I call “Hex”:

# hello_world.hex
# compiles to "hello_world.txt"

48 65 6c 6c 6f  # "Hello"
20              # space
77 6f 72 6c 64  # "world"
0a              # newline

In Hex, you can write not just programs, but videos, images, text files, anything. You write programs in Hex by writing the hexadecimal codes for each byte of, say, an ELF binary for Linux on Intel x86. These programs are completely readable, because you can also write comments.

To run a Hex program, you first pass it to the hex compiler:

$ hex < hello_world.hex > hello_world.txt
$ cat hello_world.txt
Hello world

Here is a compiler for Hex, written in C:

#include <stdio.h>
int to_hex(char c) {
  if      ('0' <= c && c <= '9') { return      c-'0'; }
  else if ('a' <= c && c <= 'f') { return 10 + c-'a'; }
  return -1;
}
int main(void) {
  for (;;) {
    int c = getchar();
    if (to_hex(c) != -1) {
      int c2 = getchar();
      if (to_hex(c2) != -1) { putchar(0x10*to_hex(c) + to_hex(c2)); }
      else { return 1; }
    }
    else if (c == EOF) { break; }
    else if (c == '#') { while (getchar() != '\n'); }
    else if (c == ' ' || c == '\n') { continue; }
    else { return 1; }
  }
  return 0;
}

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

More by Jim

Tagged . All content copyright James Fisher 2018. This post is not associated with my employer. Found an error? Edit this page.