r/C_Programming • u/imaami • Jun 09 '26
Etc New hex parsing function dropped and it's barely cursed at all
Here's a neat little hex char parsing trick. Not terribly practical, but it's not like you have anything better to do than look at it. It's only mildly atrocious.
#include <stdio.h>
static inline unsigned
from_hex_char (char c)
{
return (' '|c) % 29 % 19;
}
int
main (int c,
char **v)
{
for (int i = 1; i < c; ++i) {
unsigned long long x = 0;
for (char *p = &v[i][2 * (v[i][0] == '0' &&
(' '|v[i][1]) == 'x')]; *p; ++p) {
x <<= 4U;
x |= from_hex_char(*p);
}
(void)printf("%llu\n", x);
}
}
43
Upvotes
17
u/earwiggo Jun 09 '26
I guess this guy really hates conditionals
10
u/clickyclicky456 Jun 09 '26
That is evil. And brilliant. WTF?!
6
u/ComputerNerd2007 Jun 09 '26
Thats the first time I see someone writing the return type in another row. Do you have a specific reason to write it that way (I realy want to know)?
Thats a crazy function...
8
u/Atijohn Jun 09 '26
neat trick with the double modulo, the "skip
0xat the beginning if present" is kind of lame honestly, the rest is standard hex parsing, also the parser doesn't do any error handlingoverall 5/10, would be a 6 if it wasn't written using the GNU code style
2
u/UltimatePeace05 Jun 10 '26
oh hell nah! 2 integer divides!?
otherwie LGMT (more or less)
2
u/Linguistic-mystic Jun 11 '26
Now that's atrocious. Learn to use grown-up integer types like
uint64_t.0
u/[deleted] Jun 10 '26
[deleted] — view deleted comment
0
u/[deleted] Jun 10 '26
[deleted] — view deleted comment