Related question : Java On AND'ing a short with an short, it is upgraded to int and returns weird values
I have a short (2 bytes) space which should be used for setting 16 flags, one in each bit. I have to write an API to set/check/clear n'th bit (n = 0, 1..15). The problem comes in case of the MSBit.
I'm setting it like this:
short setBit(short flags, int n) {
flags |= (1 << n);
return flags;
}
When n is 15
I set the sign bit and resulting value is : 1111111111111111111111111111111111111111111111111000000000000000
.
I tried to fetch the lower 16 bits out of this by doing :
flags &= 0xffff;
I get the same answer which is expected as the sign bit remains the same. How do I set the highest bit and don't end up converting type and having sign bit extend/fill rest of the space? (These flags are to be written to the disk).