UIL CS: Bitwise Operations & Boolean Algebra
This is part of the UIL CS study series. See also:
Main topic list: https://www.uiltexas.org/files/academics/UILCS-JavaTopicList2526.pdf
4. Bitwise Operations (with a full example)
Operators:
&AND|OR^XOR~NOT<<left shift>>arithmetic right shift>>>logical right shift
Example expression
Compute:
int ans = (13 & 6) ^ (9 | 2);
Convert to binary:
Step 1:
1101
0110
----
0100 = 4
Step 2:
1001
0010
----
1011 = 11
Step 3: XOR: 4 \^ 11
0100
1011
----
1111 = 15
So: ans = 15
Bit shifts (with examples)
x << k: shift left by bits (multiply by , if no overflow)x >> k: arithmetic right shift by bits (divide by rounding toward , preserves sign bit)x >>> k: logical right shift by bits (fills with s, ignores sign)
Examples (binary)
Let :
Left shift
Arithmetic right shift
Logical right shift
(same as here because positive)
Negative shift example (important)
Use an 8-bit view for intuition.
Let in 8-bit two's complement:
(in 8 bits)
Arithmetic right shift
- :
- is
So
Logical right shift
- :
- which is in unsigned interpretation
So can turn negatives into huge positives.
Signed bits, one's complement, two's complement
Sign bit
In signed binary representations, the leftmost bit indicates sign:
- nonnegative
- negative (in two's complement)
One's complement
To negate: flip all bits
Example in bits:
(one's complement)
Problem: there are two zeros: ,
One's complement is mainly a historical concept; Java uses two's complement.
Two's complement (what Java uses)
To negate:
- flip all bits
- add
Example:
invert:
Why it matters
- single representation for
- subtraction becomes addition:
- addition hardware is simpler
Range in two's complement
For bits:
Example -bit signed:
5. Boolean algebra identities + symbols
- Circle-plus: means XOR
- true when inputs differ
- Overline: means NOT A (complement)
- same as
!A
- same as
Core identities (memorize)
Let OR, AND, overline NOT.
Identity laws
Domination
Idempotent
Complement
Double negation
Commutative
Associative
Distributive
De Morgan's
XOR facts
- XOR is associative/commutative
Digital symbols reference: https://www.uilexas.org/files/academics/UILCS-DigitalSymbols.pdf