Lecture 8: Bitwise Operations in C and UNIX Flashcards
Btiwse AND operator
&
How to mask something with 0s?
Bitwise AND.
Bitwise assignmetn
Example: AND
x &= int;
Octal format specifer.
%o
Bitwise OR operator
|
XOR operator
XOR to swap 2 variables
i1 ^= i2
i2 ^= i1
i1 ^= i2
This lets i1 and i2 be swapped without a temporary variable
What does ~ do?
Ones complement
Ones complement operator
~
Left and right shift operators.
«_space;and»_space;
As I recall, A«B would shift A left by B bits
Does left and right shift work with assignment?
Yes.
A«=1;
Multiplying/dividing by 2 with bit shifts.
Shift left to multiply by 2.
Shift right to multiply by 2.
Also could be extended to all powers of 2.
Arithmetic vs Logical right shift.
If there is a 0 in the left-most bit, it is always filled with a 0. If there is a 1, arithmetic fills with 1s but logical fills with 0s. This varies from machine to machine, so never assume which behavior will be used there.
What happens if you try to bit-shift by a negative amount?
Undefined behavior.
How might you find if something is a power of 2 with bitwise operators?
Figure it out.