i posted this little C code riddle earlier. so here's what it does:

1. flip all the bits in the input, so 0 becomes 1 and 1 becomes 0

2. bitwise-AND this with 1, whose binary representation is also 1. this will keep only the last bit of the number and set the rest to 0.

the result can thus only be 0 or 1. if you count in binary:

0 = ...000
1 = ...001
2 = ...010
3 = ...011
4 = ...100
5 = ...101

notice how the last bit keeps flipping for every number?

if the function was just x & 1, this would tell you if the number was odd. but if you flip all the bits before you mask it, it tells you if the number is even.

could also be written as !(x & 1)

Follow

@lore I love it. I've never looked at Z mod 2 equivalency classes in binary. The 2n class would have binary ending in zero and the 2n + 1 class would have the binary end in one. That's pretty damn interesting.

Superficially it's not that impressive but it does a lot more than it seems to. That's a very good dive into the code and explanation. It's textbook worthy, really.

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.