简体   繁体   中英

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!

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.

I am not sure if I get the question right, but your mask looks like

0x00000000000000ff
0x000000000000ffff
0x0000000000ffffff
...

I assume that you want something like the following, to mask individual bytes:

0x00000000000000ff
0x000000000000ff00
0x0000000000ff0000
...

For this, you can use eg the following code:

for( mask = 0xff; n; n--) {

    // Use the mask HERE
    ...

    mask = mask<<8;
}

You could use this code snippet, to replace the byteno th byte with dest mask, in src :

uint64_t replacemyByte(uint64_t src, uint64_t byteno,uint64_t dest) 
{
    uint64_t shift = (dest << (8 * byteno));
    uint64_t mask = 0xff << shift;
    return (~mask & src) | shift;
}

Or did I get the question wrong?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM