Study smarter with Fiveable
Get study guides, practice questions, and cheatsheets for all your subjects. Join 500,000+ students with a 96% pass rate.
Bitwise operators in C allow you to manipulate individual bits of data directly. They are essential for tasks like masking, toggling, and setting flags, making them powerful tools for efficient programming and low-level data handling.
Bitwise AND (&)
5 & 3 results in 1 (binary: 0101 & 0011 = 0001).Bitwise OR (|)
5 | 3 results in 7 (binary: 0101 | 0011 = 0111).Bitwise XOR (^)
5 ^ 3 results in 6 (binary: 0101 ^ 0011 = 0110).Bitwise NOT (~)
~5 results in -6 (binary: ~0101 = 1010 in two's complement).Left shift (<<)
5 << 1 results in 10 (binary: 0101 << 1 = 1010).Right shift (>>)
5 >> 1 results in 2 (binary: 0101 >> 1 = 0010).Bitwise assignment operators (&=, |=, ^=, <<=, >>=)
x &= y is equivalent to x = x & y, and similarly for other operators.Bitmasking
Bit manipulation techniques
x |= (1 << n) sets the nth bit, x &= ~(1 << n) clears it.Bitwise operations for flag setting and checking
flags |= FLAG_A sets FLAG_A, while flags & FLAG_A checks if FLAG_A is set.