2024-08-13 You can't comprehend this Hello World
Actually looking at it now I don't see anything difficult about this code. It was probably harder to write than it is to read. Anyway, there are few mysteries to discover:
- How "hello there" strings can fit in single 64 bit number?
- Why we need 0 at the end of this number?
- How this string is terminated and why not with 0?
- How space was encoded?
$ cat -n hello.c
1 int main(void) {
2 int putchar(int);
3 long a=0x10D03F1A77030;
4 while ((a>>=4)-1) putchar((a&15) + 101 + !(a%7)*-70);
5 return 0;
6 }
$ cc hello.c && ./a.out
hello there
This code is heavily inspired by Tsoding old obscured Hello World program [1]. The main difference is that he had 2 magic numbers, one to store set of character codes and second to point at specific character in that set. His approach allows to easily print any character. You can watch video that explains it [2].
In my version I can access only characters in range from 0 to 15 and that's why I need special handling for space and why I print "hello there" instead of "Hello World". But you probably already figured that out, right?
I CHALLENGE YOU 🫵 TO WRITE STRANGER VERSION!
Maybe something more compact, or something even less obvious, or maybe avoid using variables, or try without loops. IDK, surprise me.
Never get scared by the code. Remember, code is scared of you more then you scared of the code.
Tsoding
BTW, I also made this one:
$ cat -n hello2.c
1 int main(void) {
2 int putchar(int);
3 long unsigned a=-134494809275099426, b=123;
4 while (b += a & 0377, putchar(b), a >>= 010);
5 return 0;
6 }