Bitwise Operations in C

Bitwise operations need to be handled based on the code, and this is only for bits. This is very fast and CPU efficient. 




This post contains the following bitwise operations
1. Set bit
2. Clear bit
3. Toggle bit
4. Swap all even and odd bits



#include <stdio.h>
#define set_bit(num, bit_to_set) num |= (1 << bit_to_set)
#define clear_bit(num, bit_to_unset) num &= (~(1 << bit_to_unset))
#define toggle_bit(num, bit_to_toggle) num ^= (1 << bit_to_toggle)

int main()
{
    int num = 5; //(00000000 00000000 00000000 00000101)
    // Want to set 6th bit
    int bit_to_set = 5;  //(00000000 00000000 00000000 00100000) 
    int bit_to_unset = 2;  //(00000000 00000000 00000000 0000100)
    int bit_to_toggle = 3; //(00000000 00000000 00000000 00001000)
    int choice = 0;
    
    // Masking a Bit
    printf("The number is %d\n", num);
    printf("Set the %dth bit, and the value is %d\n", 
               bit_to_set+1, set_bit(num, bit_to_set)); 
    
    // Unmasking a Bit
    num = 20;
    printf("The number is %d\n", num);
    printf("Clear the %dth bit, and the value is %d\n", 
               bit_to_unset+1, clear_bit(num, bit_to_unset));

    // Flipping a Bit
    num = 12;
    printf("The number is %d\n", num);
    printf("Toggle the %dth bit, and the value is %d\n", 
               bit_to_toggle+1, toggle_bit(num, bit_to_toggle));
    return 0;
}

Output:
1
2
3
4
5
6
The number is 5
Set the 6th bit, and the value is 37
The number is 20
Clear the 3th bit, and the value is 16
The number is 12
Toggle the 4th bit, and the value is 4


Swap all odd and even bits (HCL Interview Questions)

#include <stdio.h>

int main()
{                   // .... .... ..16 8421
    int num = 516;  // 0000 0010 0000 0100 Input
    int result = 0; // 0000 0001 0000 1000 Output 264
    int even = 0xAAAA; //To get only the even bits
    int odd = 0x5555; //To get only the odd bits
 
    even &= num; // 0000 0010 0000 0000
    odd &= num; // 0000 0000 0000 0100
 
    even >>= 1; // 0000 0001 0000 0000
    odd <<= 1;   // 0000 0000 0000 1000

    result = even | odd; // 0000 0001 0000 1000
    printf("Result %d\n", result); 

    return 1;
}

Output:
1
Result 264

If the last most bit is set which is 2^15, it will not be neglected. Since it is even bit, it will right shifted, so it will be moved to 2^14 th bit. 

Reference: Geeksforgeeks

Comments