<aside> <img src="/icons/home_green.svg" alt="/icons/home_green.svg" width="40px" />

Back to Home

</aside>

https://jennychen9827sbu.github.io/CAD281/bitwise.html

Bitwise Manipulate Reference

Basic Bitwise Operators

1. Basic Bit Operations

unsigned char value = 0xA5;    // 10100101 in binary
unsigned char position = 3;    // bit position to manipulate

// Set bit at position
value |= (1 << position);     // Sets bit 3 to 1

// Clear bit at position
value &= ~(1 << position);    // Sets bit 3 to 0

// Flip/Toggle bit at position
value ^= (1 << position);     // Flips bit 3

// Check if bit is set
if (value & (1 << position)) {
    printf("Bit is set\n");
}

2. Simple Multiplication Using Left Shift

int num = 5;
int power = 3;
int result = num << power;  // 5 * 8 = 40 (shifting left 3 positions)

3. Simple Division Using Right Shift

unsigned int num = 20;
int power = 2;
unsigned int result = num >> power;  // 20 / 4 = 5 (shifting right 2 positions)

4. Simple Number Swapping Using XOR

int x = 5, y = 10;
x = x ^ y;    // x becomes x XOR y
y = x ^ y;    // y gets original value of x
x = x ^ y;    // x gets original value of y

5. Working with Masks

A mask is a binary pattern used to extract or modify specific bits: