Reputation: 7940
I am using Java's primitive long data type to store a flag. long has 8 bytes so 64 bit with high order bit representing the sign bit so we have 63 usable bit as a flag. Everything works until I turn on 32nd bit yields -1. Why is this happening?
Edit: Basically I am trying to flag the availability in an hour for first 60 bit (1 bit representing a minutes in an hour) on long data type. Let's assume start time is 0:0:00. Everything works if the end time is up to 0:30:00 but fails with 0:31:00 up to 60 minutes, meaning when I attempt to (value & (1 << 31)) for some value initialized to 0 this will not return 2^31 rather it returns -1.
Edit: Declaring a mask as 1L rather than 1 solved the problem.
Upvotes: 0
Views: 226
Reputation: 719596
I think this is your bug:
(1 << mIndex)
That is performing a shift on a 1
which is an int
. If you perform a shift on an int
, the result will be an int
, even if the 2nd operand is greater than 32.
Try this instead:
(1L << mIndex)
Upvotes: 3
Reputation: 3569
Agreed with Lawrence Kesteloot, but if you still have no luck this may be a bug in your JVM implementation. You may also have better luck using the java.util.BitSet
class.
Upvotes: -1
Reputation: 4398
You should paste your code, but my guess is that you've got an "int" somewhere in your math, and that's getting turned into -1 before it gets cast to a long.
Upvotes: 3