Hello I am really new to C language and recently asked for code help on stack overflow and a really really brilliant person gave me this code.
for(int m = 1; m < 262144; m <<= 1) putc("\n12345"[!!(96221 & m) + !!(26520 & m) + !!(18192 & m) + !!(1536 & m) + !!(1024 & m)], stdout);
Which prints out
1
123
12345
123
1
This was exactly what I was looking for.
However I do not understand how this code works. And I have google’d those things above but I can not find/ understand it.
Especially with
‘
<<=,All those weird ginormous numbers.
‘
these two.
So, can someone explain how this code works? And explain what each part of the codes are?
I would really appreciate your help. Thankyou.
>Solution :
I’m not sure the person who gave you this code was brilliant so much as devious… this looks like deliberately obfuscated code 🙂
m <<= 1
The above means "shift the bits in m left by one position", which has the effect of multiplying m by 2.
putc(..., stdout);
putc( is a function to print a single character to a file (in this case, to stdout)
"\n12345"[!!(96221 & m) + !!(26520 & m) + !!(18192 & m) + !!(1536 & m) + !!(1024 & m)]
This line computes the character to print. "\n12345" is an array of characters to choose from, and then the text inside the [brackets] is computing an index (between 0 and 5) into that array; the character at that index will be the one that is printed.
The !! prefixes are double-applications of the boolean not-operator, used to convert the value in parentheses to 1 if it was non-zero and to 0 if it was zero.
The (blah & m) pieces are checking the given integer-constant to see if a particular bit is set in that constant, or not. If the particular bit is set, 1 is added to the sum that will be used to calculate the index into the array. I don’t think I’m smart enough to give more details on why those particular numeric values were chosen 🙂