Devilish Code
I'm a big fan of The Daily WTF, which showcases examples of bad programming that would cause a normal person to exclaim, "what the fuck?" The posts themselves are often entertaining, but the real value is generally to be found in the comments, where people often post alternative solutions that are sometimes brilliant and sometimes equally (deliberately) WTFic.
A recent article showed a piece of unnecessarily long-winded code, the effect of which was to return the given integer if it was in the range 0–3, or 0 otherwise. An alternative implementation of this was posted in the comments, with the warning that it contained "added evilness":
int getmessage (int c)
{
return (!(c&~3))["(c&3)"]&c&3;
}
In C, & is the binary and operator, and ~ the binary not. So !(c&~3) will be 1 if c is in the range 0–3 and 0 otherwise. So far, so binary arithmetic.
Next is the tricky bit. C has an odd quirk that a[b] is equivalent to b[a]. This means that (!(c&~3))["(c&3)"] is the same as "(c&3)"[(!(c&~3))]. This is a normal character array element: just as "abc"[0] is 'a', "(c&3)"[(!(c&~3))] will give 'c' if c is in the range 0–3, '(' otherwise. The rest of that string is just there to confuse you. In fact, it's not even important that the first two characters are what they are. They only have to satisfy a certain condition I'll describe next.
Whichever character you get at this point is anded with c&3, the lowest two bits of c. Look at the binary representation of the characters 'c' and '(': 'c' == 01100011b and '(' == 00101000b. The low two bits are the important ones in both cases. They are both 1 for 'c' and both 0 for '('.
If your input to the function was in the right range, it'll be expressed only in those low two bits, it will be anded with 'c' which has 1s in both low bits, and with 3, which also has 1s in both low bits. The result is that you get back the number you put in.
If your input was out of that range, it'll be anded with '('&3. That expression is 0, because '(' has 0s in the low two bits, and 3 has 0s everywhere else. Anything anded with 0 gives 0, so the overall result is 0.
I've come to terms with the fact that I have the kind of mind that likes to figure out why this works, but I'm still bemused by the type of mind that invents this kind of evilness.
Comments:
Sat, 03rd Feb 2007 (11:59)