1

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.

Evg
  • 25,259
  • 5
  • 41
  • 83
Kyy13
  • 315
  • 1
  • 9
  • 7
    You might want to try `1ULL` instead of `1`. – njuffa Sep 08 '18 at 04:07
  • Can you print the results in hex please, I have no idea what I'm looking at. – harold Sep 08 '18 at 04:10
  • what's wrong with overflowing the unsigned long long int? – Ap31 Sep 08 '18 at 04:15
  • @Ap31 bitMask = (1 << bitLength) - 1 produces 0 at bitLength = 64. – Kyy13 Sep 08 '18 at 04:18
  • @njuffa that works. thank you. I guess my compiler automatically converted in A but not B. – Kyy13 Sep 08 '18 at 04:19
  • What values you expect to get? – Amit G. Sep 08 '18 at 04:33
  • 5
    @Kyy13 [shifting more than the width of the type invokes UB](https://stackoverflow.com/q/11270492/995714), so all bets are off – phuclv Sep 08 '18 at 04:46
  • What is `bitLength` defined as? – Ulrich Eckhardt Sep 08 '18 at 05:51
  • there are a lot of duplicates: [bit shifting with unsigned long type produces wrong results](https://stackoverflow.com/q/31744305/995714), [Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times?](https://stackoverflow.com/q/7401888/995714), [Bitwise Leftshift (<<) strange behavior](https://stackoverflow.com/q/16879251/995714), [Bitwise shift in C](https://stackoverflow.com/q/46769196/995714) – phuclv Sep 08 '18 at 05:53
  • @phuclv My question is not a duplicate of those questions, because I am not shifting by more than the width of the type. unsigned long long = (1 << 63) + ( (1 << 63) - 1) where the width if the type is 64 bits long. – Kyy13 Sep 08 '18 at 17:50
  • 1
    @Kyy13 read those questions carefully. `1 << 63` shifts more than the type's width unless you're on a platform with 64-bit (or wider) int, because [1 is an `int` literal](https://stackoverflow.com/a/23858905/995714). Did you see njuffa's comment above? Some other duplicates: [printf 64bit type specifier issue](https://stackoverflow.com/q/16415691/995714), [Compute signed long max value in C using bit shift](https://stackoverflow.com/q/41418472/995714) – phuclv Sep 09 '18 at 00:37

0 Answers0