I'm trying to understand why bitMaskB
is incorrect. It works with every number except for bitLength = 64
. The reason I have it this way instead of (1 << bitLength) - 1
is to support bitLength = 64
without overflowing the unsigned long long int
.
unsigned long long bitMaskA = ((1 << (bitLength - 1)) - 1)
+ (1 << (bitLength - 1));
unsigned long long bitMaskB = 1 << (bitLength - 1);
bitMaskB = (bitMaskB - 1) + bitMaskB;
std::cout << bitMaskB << std::endl; // 18446744069414584319
std::cout << bitMaskA << std::endl; // 18446744073709551615
std::cout << 0xffffffffffffffff << std::endl; // 18446744073709551615
UPDATE:
I fixed the problem by doing (bitMaskB - 1) | bitMaskB
instead, but I would still like to know why this happens.