C MoreLesson 54Free preview
C Bitwise Operators
This lesson is part of C · All levels
Summary
The bitwise operator works per bit AND (&), OR (depending), XOR (^ NOT (~), left slide (<<), and right slide (>>). This operator is useful for setting flags, saving memory with bit fields, and processing low-level data such as network protocols or binary formats. The general technique you need to master is to adjust, remove, reverse, and test one bit using a mask.
Key points
- Set bits: x, one k; delete bits: x and k; return bits: x^ (1 k); test bits: x >> k and 1.
- & produces 1 only when both bits are equal to 1, and ^ produces 1 when both are different.
- The left slide << magnifies the value of the multiplication 2, while the right slide >> divides it, with an overflow record and a negative number.
- Use a hexadecimal mask like 0xFF to separate the desired byte.
- In negative numbers, the result depends on the representation of the sign so it is safer to use the type without the sign.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.