20 Bitwise
20 Bitwise
Ethan Blanton
Department of Computer Science and Engineering
University at Buffalo
Introduction Bit Operations C Bit Manipulation Example Summary References
Bitwise Operations
We have seen arithmetic and logical integer operations.
They are often related to, yet different from, logical operations.
Planning: Documentation
How do you absorb the documentation?
Read:
The handout
The README/etc.
The given code and its comments
Truth Tables
You should already be familiar with truth tables.
A truth table represents one or two input bits and their output bit.
x y Result
0 0 0
1 0 1
0 1 1
1 1 1
Bitwise Operations
OR (∨):
AND (∧):
x y Result
0 0 0 x y Result
1 0 1 0 0 0
0 1 1 1 0 0
1 1 1 0 1 0
1 1 1
XOR (⊕):
NOT (¬):
x y Result
0 0 0 x Result
1 0 1 0 1
0 1 1 1 0
1 1 0
© 2021 Ethan Blanton / CSE 220: Systems Programming 5
Introduction Bit Operations C Bit Manipulation Example Summary References
∀n−1
i=0 Resulti = xi ⊕ yi
Bit Shifting
Bit shifts are slightly more complicated.
Examples:
0111 left shift 1 bit → 1110
0010 left shift 2 bits → 1000
Right Shifts
Right shifts are somewhat trickier.
If the shifted integer is signed, the sign bit may affect the shift.
If it is zero, shifts behave as unsigned
If it is one, it might shift in ones
Operators
The C bitwise operators divide into unary and binary operators:
Unary:
~x: Bitwise complement of x (0 → 1, 1 → 0)
Binary:
x | y: Bitwise OR of x and y
x & y: Bitwise AND of x and y
x ^ y: Bitwise XOR of x and y
x << y: Left shift x by y bits
x >> y: Right shift x by y bits
Not (~) and and (&) are particularly pernicious because they
often work.
Masking
Many bitwise operations are used to work on a portion of a word.
Bit Twiddling
Setting and unsetting individual bits typically uses masking.
x = x | LOWBIT ;
x y Result
0 0 0
1 0 1
0 1 1
1 1 0
x = x ^ LOWBIT ;
Forcing Endianness
htonl in Action
int x = 0 x01020304 ;
int y = htonl ( x ) ;
04 03 02 01
01 02 03 04
Summary
References I
Required Readings
[1] Randal E. Bryant and David R. O’Hallaron. Computer Science: A Programmer’s
Perspective. Third Edition. Chapter 2, 2.1.6–2.1.9. Pearson, 2016.
[2] Brian W. Kernighan and Dennis M. Ritchie. The C Programming Language. Second
Edition. Chapter 2, 2.9, Appendix A, A7.4.6, A7.8, A7.11–A7.13. Prentice Hall, 1988.
License