0

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!

musicmatze
  • 4,124
  • 7
  • 33
  • 48

3 Answers3

2

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • No he's not - << takes precedence over |. (you did read that link yourself?). It would only fail if he used + instead of | – Pete Jan 24 '13 at 10:39
  • Actually I retract the -1 because adding the brackets is still better coding style. – Pete Jan 24 '13 at 10:39
  • @Pete Thanks, I was actually a bit uncertain but didn't take the time to test. I tried to express that, but not very clearly. Rewritten. – unwind Jan 24 '13 at 10:45
1

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 e.g. the following code:

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

    // Use the mask HERE
    ...

    mask = mask<<8;
}
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
0

You could use this code snippet, to replace the bytenoth 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?

askmish
  • 6,464
  • 23
  • 42