Bitwise Operations in C
Bitwise operations allow you to manipulate individual bits of data. They are useful for tasks such as setting/clearing specific bits, checking bit flags, or performing bitwise logical operations.
#include <stdio.h>
int main() {
unsigned int flags = 0b1010; // Binary representation: 1010
// Setting bit 2 (third bit) to 1
flags |= (1 << 2);
// Clearing bit 0 (first bit)
flags &= ~(1 << 0);
// Checking if bit 3 (fourth bit) is set
if (flags & (1 << 3)) {
printf("Bit 3 is set.\n");
}
// Toggling bit 1 (second bit)
flags ^= (1 << 1);
// Printing the resulting flags value
printf("Flags: %u\n", flags);
return 0;
}
No comments:
Post a Comment