# bit

***

**1. Bitmasking for Flag Handling**

```c++
const int FLAG_A = 1 << 0;
const int FLAG_B = 1 << 1;
const int FLAG_C = 1 << 2;

int flags = FLAG_A | FLAG_C; // Set flags A and C
bool isFlagASet = (flags & FLAG_A) != 0; // Check if flag A is set
```

**2. Binary Search Tree Node Flags**

```c++
class Node {
public:
    bool isDeleted;
    bool isBalanced;
};
```

**3. Bitwise Multiplication and Division**

```c++
// Multiply by 2
int num = 10;
num <<= 1; // num is now 20

// Divide by 2
num >>= 1; // num is now 10
```

**4. Bitwise XOR for Swapping Variables**

```c++
int a = 10, b = 20;
a ^= b; // a is now 30
b ^= a; // b is now 10
a ^= b; // a is now 20
```

**5. Bitwise AND and OR for Bitwise Filtering**

```c++
// Filter odd numbers
vector<int> nums = {1, 2, 3, 4, 5};
vector<int> oddNums;
for (int num : nums) {
    if ((num & 1) != 0) {
        oddNums.push_back(num);
    }
}
```

**6. Bitwise NOT for Negation**

```c++
int num = 10;
int neg = ~num; // neg is now -11
```

**7. Bitwise Rotation for Circular Arrays**

```c++
// Rotate an array to the right by k positions
vector<int> arr = {1, 2, 3, 4, 5};
int k = 2;
rotate(arr.begin(), arr.begin() + arr.size() - k, arr.end());
```

**8. Bitwise Shifting for Exponential Calculations**

```c++
// Calculate 2^5
int result = 1 << 5; // result is now 32
```

**9. Bitwise Conversion for Character to Integer**

```c++
char ch = 'a';
int intVal = ch - 'a' + 1; // intVal is now 1
```

**10. Bitwise Masking for Data Alignment**

```c++
// Align a 16-bit value to a 32-bit boundary
uint16_t value = 0x1234;
uint32_t alignedValue = value << 16;
```

**11. Bitwise Optimization for Character Counting**

```c++
// Count the number of 'a' characters in a string
string str = "This is a test string";
int count = 0;
for (char ch : str) {
    if ((ch ^ 'a') == 0) {
        count++;
    }
}
```

**12. Bitwise Matrix Multiplication**

```c++
// Multiply two binary matrices
vector<vector<int>> matrixA = {{1, 0}, {0, 1}};
vector<vector<int>> matrixB = {{0, 1}, {1, 0}};
vector<vector<int>> resultMatrix(2, vector<int>(2));
for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 2; j++) {
        resultMatrix[i][j] = (matrixA[i][0] & matrixB[0][j]) | (matrixA[i][1] & matrixB[1][j]);
    }
}
```

**13. Bitwise Hashing for Key Value Stores**

```c++
// Hash a key using bitwise operations
string key = "key";
uint64_t hash = 0;
for (char ch : key) {
    hash ^= (hash << 5) + ch;
}
```

**14. Bitwise Optimization for Range Checking**

```c++
// Check if a number is between two values using bitwise operations
int num = 10;
int min = 5;
int max = 15;
bool isInRange = ((num - min) & (max - num)) == 0;
```

**15. Bitwise Tricks for Data Compression**

```c++
// Encode a positive integer using unary encoding
vector<bool> encoded;
for (int i = 0; i < num; i++) {
    encoded.push_back(true);
}
encoded.push_back(false);
```

**16. Bitwise Manipulation for Geometric Calculations**

```c++
// Check if a point is inside a rectangle
Point point = {10, 20};
Rectangle rect = {{0, 0}, {10, 10}};
bool isInside = (point.x >= rect.topLeft.x) && (point.x <= rect.bottomRight.x) &&
                 (point.y >= rect.topLeft.y) && (point.y <= rect.bottomRight.y);
```

**17. Bitwise Masking for Image Processing**

```c++
// Extract the red component from an RGB pixel
Pixel pixel = {255, 0, 0};
uint8_t red = pixel.color & 0xFF;
```

**18. Bitwise Tricks for Data Structures**

```c++
// Create a hash table using a bit array
vector<bool> bitArray(1000000, false);
void insert(int key) {
    bitArray[key] = true;
}
bool find(int key) {
    return bitArray[key];
}
```

**19. Bitwise Optimization for Sorting**

```c++
// Sort an array of integers using bitwise counting sort
vector<int> arr = {1, 4, 3, 2, 5};
int maxVal = *max_element(arr.begin(), arr.end());
vector<int> count(maxVal + 1, 0);
for (int num : arr) {
    count[num]++;
}
int idx = 0;
for (int i = 0; i <= maxVal; i++) {
    while (count[i]--) {
        arr[idx++] = i;
    }
}
```

**20. Bitwise Encryption**

```c++
// Encrypt a message using bitwise XOR
string message = "Hello World";
string key = "Secret";
string encryptedMessage;
for (int i = 0; i < message.length(); i++) {
    encryptedMessage += message[i] ^ key[i % key.length()];
}
```

**21. Bitwise Optimization for String Comparison**

```c++
// Compare two strings using bitwise operations
string str1 = "Hello";
string str2 = "World";
bool isEqual = (str1.length() == str2.length()) && (str1[0] ^ str2[0] == 0) &&
               (str1[1] ^ str2[1] == 0) && (str1[2] ^ str2[2] == 0) && (str1[3] ^ str2[3] == 0) &&
               (str1[4] ^ str2[4] == 0);
```

**22. Bitwise Tricks for Floating-Point Calculations**

```c++
// Get the sign bit of a floating-point number
float num = -5.0f;
int sign = (int)(num == 0 ? 0 : (num > 0 ? 1 : -1));
```

**23. Bitwise Optimization for Function Overloading**

```c++
template <typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}
```

**24. Bitwise Tricks for Bit Manipulation**

```c++
// Set the kth bit of a number
int num = 10;
int k = 3;
int result = num | (1 << (k - 1));
```

**25. Bitwise Computation for Mathematical Functions**

```c++
// Calculate the greatest common divisor (GCD) using bitwise operations
int gcd(int a, int b) {
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}
```

**26. Bitwise Optimization for Conditional Execution**

```c++
// Execute a block of code only if a condition is met
int num = 10;
if (num > 0) {
    // Code to be executed
}
```

**27. Bitwise Tricks for Memory Management**

```c++
// Check if a pointer is aligned to a specific boundary
void* ptr = malloc(sizeof(int));
bool isAligned = ((uintptr_t)ptr & (uintptr_t)(boundary - 1)) == 0;
```

**28. Bitwise Optimization for Atomic Operations**

```c++
// Atomically increment a variable using bitwise operations
atomic<int> counter;
counter.fetch_add(1, memory_order::relaxed);
```

**29. Bitwise Techniques for Concurrency**

```c++
// Use bitwise operations to implement a spinlock
atomic<int> lock;
while (lock.load(memory_order::relaxed) != 0) {
    // Spin until the lock is acquired
}
lock.store(1, memory_order::relaxed);
```

**30. Bitwise Tricks for Algorithm Design**

```c++
// Use bitwise operations to implement a counting sort algorithm
vector<int> arr = {1, 4, 3, 2, 5};
int maxVal = *max_element(arr.begin(), arr.end());
vector<int> count(maxVal + 1, 0);
for (int num : arr) {
    count[num]++;
}
int idx = 0;
for (int i = 0; i <= maxVal; i++) {
    while (count[i]--) {
        arr[idx++] = i;
    }
}
```

**31. Bitwise Optimization for Tree Traversals**

```c++
// Use bitwise operations to implement a non-recursive inorder traversal of a binary tree
void inorderTraversal(BinaryNode* root) {
    stack<BinaryNode*> stack;
    BinaryNode* curr = root;
    while (curr || !stack.empty()) {
        while (curr) {
            stack.push(curr);
            curr = curr->left;
        }
        curr = stack.top();
        stack.pop();
        visit(curr->data);
        curr = curr->right;
    }
}
```

**32. Bitwise Techniques for Performance Optimization**

```c++
// Use bitwise operations to implement a fast exponentiation algorithm
int fastPow(int base, int exponent) {
    int result = 1;
    while (exponent > 0) {
        if ((exponent & 1) != 0) {
            result *= base;
        }
        base *= base;
        exponent >>= 1;
    }
    return result;
}
```

**33. Bitwise Tricks for Data Structures**

```c++
// Use bitwise operations to implement a bloom filter
vector<uint64_t> bloomFilter(size_t numBits) {
    return vector<uint64_t>(numBits / 64 + 1, 0);
}
void add(const string& item, vector<uint64_t>& bloomFilter) {
    uint64_t hash1 = hashFunction1(item);
    uint64_t hash2 = hashFunction2(item);
    bloomFilter[hash1 / 64] |= (1ULL << (hash1 % 64));
    bloomFilter[hash2 / 64] |= (1ULL << (hash2 % 64));
}
bool mightContain(const string& item, const vector<uint64_t>& bloomFilter) {
    uint64_t hash1 = hashFunction1(item);
    uint64_t hash2 = hashFunction2(item);
    return (bloomFilter[hash1 / 64] & (1ULL << (hash1 % 64))) != 0 &&
           (bloomFilter[hash2 / 64] & (1ULL << (hash2 % 64))) != 0;
}
```

**34. Bitwise Optimization for Input and Output Operations**

```c++
// Use bitwise operations to implement a fast integer to string conversion
string intToString(int num) {
    char buf[20];
    int i = 19;
    if (num < 0) {
        num *= -1;
        buf[i--] = '-';
    }
    do {
        buf[i--] = '0' + (num % 10);
        num /= 10;
    } while (num > 0);
    return string(&buf[i + 1]);
}
```

**35. Bitwise Techniques for Graph Algorithms**

```c++
// Use bitwise operations to implement a depth-first search on a graph
void dfs(GraphNode* node, vector<GraphNode*>& visited) {
    visited.push_back(node);
    for (GraphNode* neighbor : node->neighbors) {
        if (find(visited.begin(), visited.end(), neighbor) == visited.end()) {
            dfs(neighbor, visited);
        }
    }
}
```

**36. Bitwise Tricks for Memory Allocation**

```c++
// Use bitwise operations to implement a custom memory allocator
struct Block {
    size_t size;
    uint8_t* data;
    Block* next;
};
Block* freeList = nullptr;
void* myMalloc(size_t size) {
    // Round up the size to the nearest multiple of 8 bytes
    size = (size + 7) & ~7;
    Block* block = freeList;
    while (block) {
        if (block->size >= size) {
            freeList = block->next;
            block->next = nullptr;
            return block->data;
        }
        block = block->next;
    }
    // If no suitable block was found in the free list, allocate a new one
    block = (Block*)malloc(sizeof(Block) + size);
    block->size = size;
    block->data = (uint8_t*)(block + 1);
    block->next = nullptr;
    return block->data;
}
void myFree(void* ptr) {
    Block* block = (Block*)((uint8_t*)ptr - sizeof(Block));
    block->next = freeList;
    freeList = block;
}
```

**37. Bitwise Optimization for String Search**

```c++
// Use bitwise operations to implement a fast string search algorithm
bool stringMatch(const string& text, const string& pattern) {
    size_t n = text.length();
    size_t m = pattern.length();
    uint32_t hashPattern = 0;
    for (int i = 0; i < m; i++) {
        hashPattern = (hashPattern << 8) | (pattern[i]);
    }
    uint32_t hashWindow = 0;
    for (int i = 0; i < n; i++) {
        hashWindow = (hashWindow << 8) | (text[i]);
        if (i >= m - 1) {
            if (hashWindow == hashPattern) {
                return true;
            }
            hashWindow = hashWindow & ~(1ULL << 8 * (m - 1));
        }
    }
    return false;
}
```

**38. Bitwise Techniques for Data Compression**

```c++
// Use bitwise operations to implement a Huffman encoding algorithm
struct HuffmanNode {
    uint8_t symbol;
    uint32_t frequency;
    HuffmanNode* left;
    HuffmanNode* right;
};
HuffmanNode* buildHuffmanTree(const vector<uint8_t>& symbols, const vector<uint32_t>& frequencies) {
    priority_queue<HuffmanNode*, vector<HuffmanNode*>, greater<HuffmanNode*>> pq;
    for (size_t i = 0; i < symbols.size(); i++) {
        pq.push(new HuffmanNode{symbols[i], frequencies[i], nullptr, nullptr});
    }
    while (pq.size() > 1) {
        HuffmanNode* left = pq.top();
        pq.pop();
        HuffmanNode* right = pq.top();
        pq.pop();
        HuffmanNode* parent = new HuffmanNode{0, left->frequency + right->frequency, left, right};
        pq.push(parent);
    }
    return pq.top();
}
void generateHuffmanCodes(HuffmanNode* root, vector<uint8_t>& codes, vector<uint8_t>& lengths, string& code) {
    if (!root) {
        return;
    }
    if (!root->left && !root->right) {

```
