How does bitwise manipulation work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How does bitwise manipulation work?

1st Sep 2023, 4:02 AM
Jai
1 Answer
+ 2
Bitwise manipulation in C involves using operators to alter individual integer bits. Key operators are: & (Bitwise AND): Bits from both numbers result in 1 only if both bits are 1. | (Bitwise OR): Bits from either number result in 1 if either or both bits are 1. ^ (Bitwise XOR): Bits differ between numbers, resulting in 1, otherwise 0. ~ (Bitwise NOT): Inverts all bits in an integer. << (Left Shift): Moves integer bits left by a specified count. >> (Right Shift): Shifts integer bits right by a set count. These operators manipulate bits within integers for flag-setting, field extraction, memory optimization, etc. For instance, tasks include bit checks, toggling bits, and more. Example: #include <stdio.h> int main() { int num = 5; // Binary: 0101 int mask = 1 << 3; // Create a mask with the 3rd bit set (00001000) num = num | mask; // Set the 3rd bit using bitwise OR printf("Result: %d\n", num); // Output: Result: 13 (Binary: 1101) return 0; }
1st Sep 2023, 4:11 AM
Jan Markus