Search code examples
cbytemaskmaskingbitmask

Mask by n bytes


I struggle masking a uint64_t variable by N bytes. I do not know N but I know it is 8 or less. My current code looks like this:

// uint64_t n is given
uint64_t mask;
for( mask = 0x00; n; n--) {
    mask = mask<<8 | 0xFF;
}

for building the mask. What am I doing wrong here?

Edit:
The question was answered. Anyway, for better understanding:

I want a mask like this:

0x000000FF // or:
0x0000FFFF // or:
0x00FFFFFF

to take 1, 2 or more byte from the data. As the comments say, my code works! Maybe I had an bug anywere else!


Solution

  • It should work, according to the [operator precendence table1].

    Still, it's more clear to write it as:

    mask <<= 8;
    mask |= 0xff;
    

    or:

    mask = (mask << 8) | 0xff;
    

    You can also do it with a look-up table, of course.