Search code examples
cbit-manipulationterminologymaskingbitmask

Is bit masking comparable to "accessing an array" in bits?


For all the definitions I've seen of bit masking, they all just dive right into how to bit mask, use bitwise, etc. without explaining a use case for any of it. Is the purpose of updating all the bits you want to keep and all the bits you want to clear to "access an array" in bits?


Solution

  • Is the purpose of updating all the bits you want to keep and all the bits you want to clear to "access an array" in bits?

    I will say the answer is no.

    When you access an array of int you'll do:

    int_array[index] = 42;  // Write access
    int x = int_array[42];  // Read access
    

    If you want to write similar functions to read/write a specific bit in e.g. an unsigned int in a "array like fashion" it could look like:

    unsigned a = 0;
    set_bit(a, 4);   // Set bit number 4
    unsigned x = get_bit(a, 4); // Get bit number 4
    

    The implementation of set_bit and get_bit will require (among other things) some bitwise mask operation.

    So yes - to access bits in an "array like fashion" you'll need masking but...

    There are many other uses of bit level masking.

    Example:

    int buffer[64];
    unsigned index = 0;
    
    void add_to_cyclic_buffer(int n)
    {
        buffer[index] = n;
        ++index;
        index &= 0x3f;  // Masking by 0x3f ensures index is always in the range 0..63
    }
    

    Example:

    unsigned a = some_func();
    
    a |= 1;  // Make sure a is odd
    a &= ~1; // Make sure a is even
    

    Example:

    unsigned a = some_func();
    
    a &= ~0xf;  // Make sure a is a multiple of 16
    

    This is just a few examples of using "masking" that has nothing to do with accessing bits as an array. Many other examples can be made.

    So to conclude:

    Masking can be used to write functions that access bits in an array like fashion but masking is used for many other things as well.