This is really a basic question, but I never convinced myself that my intuitive answer βdoesn't matterβ is correct, so maybe someone has a good way to figure this out:
If all I want to do with one of the primitive numeric types in Java is bitwise arithmetic, can I just process it as if it were an unsigned value, or I need to avoid negative numbers, i.e. always keep the highest order bit set to 0? For example, is it possible to use int as if it were a 32-bit unsigned number, or should I use only the least significant 31 bits?
I am looking for the most general answer possible, but let me give you an example: let them say that I want to store 32 flags. Can I store all of them in one int if I use something like
store = store & ~(1 << index) | (value << index)
set the index flag to value and something like
return (store & (1 << index)) != 0
to get the index flag? Or can I run into any problems with this or similar code if I ever set the flag from index 31 to 1?
I know that I always need to use β> instead of β for the right offset, but is this the only problem? Or can there be other things wrong related to two additional representations of negative numbers when I use the most significant bit?
source share