Skip to content

C Portability Gotcha Part 2

August 22, 2012

Given the following macro:

#define BITFIELD_MASK(len) ((~static_cast<uint64_t>(0)) >> (64 - (len)))

What does this code do?

printf("%llx\n", BITFIELD_MASK(64));
printf("%llx\n", BITFIELD_MASK(32));
printf("%llx\n", BITFIELD_MASK(16));
printf("%llx\n", BITFIELD_MASK(8));
printf("%llx\n", BITFIELD_MASK(0));

I would expect to see something like:

ffffffffffffffff
ffffffff
ffff
ff
0

And that’s what I see when run on an ARM processor. But try it on an Intel and:

ffffffffffffffff
ffffffff
ffff
ff
ffffffffffffffff

I guess the Intel just decides to switch from logical to illogical shift when the number of bits shifted is 64. Apparently, what it is actually doing is choosing to shift by the value MOD the word size.

No comments yet

Leave a Reply

Your email address will not be published. Required fields are marked *