10) BITWISE Operators¶
&: AND. Only 1 when both inputs are 1 (This statement is only true, if a is true AND b is true).|: OR. Outputs 1 when either is 1 (If a is true OR be is true, then this statement is true).^: XOR. Outputs 1 when inputs are different. 0 0, and 1 1, both output 0. 1 0, and 0 1, both output 1.<<: Left Shift. Moves all bits to the left. Data is truncated if bits exist at the very left end. Don’t confuse this with the<<ofcin, the symbol is the same but the way you use it is different. You’ll see examples later. If data isn’t truncated, the effect is that the value gets multiplied by two (It’s the same as moving all values in a number to the left then adding a 0 at the end. Literally the exact same thing. This is a number system after all. 452.0 vs 4520).>>: Right Shift. Moves all bits to the right. Data is truncated if bits exist at the very right end. Don’t confuse this with the>>ofcout, the symbol is the same but the way you use it is different. You’ll see examples later. If data isn’t truncated, the effect is that the value gets divided by two (It’s the same as moving all values in a number to the right then adding a 0 at the end. Literally the exact same thing. This is a number system after all. 23000 vs 02300).~: Bitwise Complement. Flips all bits. The formula for finding out new value, ifais the variable this is applied on, is -(a+1). This works both ways. If for example the value ofais 14, then~awould be -15. If instead the value ofais-15, then the value of~awould be -(-15+1) which is -(-14) which is 14. This is a One’s Complement form. If you want the actual negative value you need to actually add one to it. Look up how Two’s Complement works.
x into a 1, you just do x = x | 1. If you want to do the second bit, it’s x = x | 2, or x = x | (1 << 1). Then let’s say you want to do the 8th bit. That would be x = x | 256 but you have to calculate that. It would be easier to just do x = x | (1 << 7). It’s one less than the bit you want to flip as 1 is in the starting position already. x = x | 1 is actually x = x | (1 << 0).Practice Exercises¶
Add two numbers using only BITWISE functions, without the use of IF statements and without the use of LOOPS
Turn all bits to the right of the most significant bit into 1
Find most significant bit of a number
Turn all consecutive bits at the end of a number into 0’s
Input a position then flip a bit at that specific position