What's the most efficient way to make bitwise operations in a C array

后端 未结 3 1941
死守一世寂寞
死守一世寂寞 2021-02-08 13:24

I have a C array like:

char byte_array[10];

And another one that acts as a mask:

char byte_mask[10];

I would

3条回答
  •  一整个雨季
    2021-02-08 14:15

    If you want to make it faster, make sure that byte_array has length that is multiple of 4 (8 on 64-bit machines), and then:

    char byte_array[12];
    char byte_mask[12];
    /* Checks for proper alignment */
    assert(((unsigned int)(void *)byte_array) & 3 == 0);
    assert(((unsigned int)(void *)byte_mask) & 3 == 0);
    for (i = 0; i < (10+3)/4; i++) {
      ((unsigned int *)(byte_array))[i] &= ((unsigned int *)(byte_mask))[i];
    }
    

    This is much faster than doing it byte per byte.

    (Note that this is in-place mutation; if you want to keep the original byte_array also, then you obviously need to store the results in another array instead.)

提交回复
热议问题