I am creating a method that takes 3 integers (start, end, z), the result should be a mask of either 1 or 0 depending on z from start to end.
For example, if getMask(2,6,1) is called the result is: 00000000000000000000000001111100
For some reason when I call getMask(0,31,1) I get: 00000000000000000000000000000000 instead of 11111111111111111111111111111111
My method code is:
if (z == 1) { return ~(~0 << (end - start + 1)) << (start); } else if (z == 0) { return ~(~(~0 << (end - start + 1)) << (start)); } I want to know why I would be getting that result instead of the expected one.
Edit: So i understand why it is happening but how do I fix it?
int, which is likely 32 bits on your system. Unsigned shifting is performed modulo number of bits, but signed shifts (what you're doing) are undefined behavior if you shift >= the number of total bits. Reference