I came across this odd piece of code today:
data[4] = (char)((1<<7) + (1<<5));
Can you figure out what it’s doing? It took me a while as well.
It’s doing a bitwise-OR of the data. But this ONLY works because of how the bits are shifted. In this particular case, it does a bitwise-OR because no bits overflow. For example, in base-10, if we have two numbers that we are adding together, and one of the numbers is 0, we can essentially just ignore it and put the two numbers together(in this example, the 1s place and 10s place only have one number each in them, so you can basically just combine them):
103
+ 20
123
You can do the same thing with binary numbers:
1010
+ 01
1011
Note that because there is no overflow in any place, this will have the same result if you do an add or a bitwise-OR together. Clearly, if there are two bits in the same position in both numbers and you add them together, that will give you a different answer than if you or them together.
Leave a Reply