I'm trying to take four bytes from a binary file and turn them into a bit mask that represents a zero for data and a 1 for metadata.
I'm assuming I need to convert them into an int by or'ing them together and then bit shift through that to determine if a bit position is set or not.
I can't work out how to combine all four together to get a 32-bit mask that I can step though.
int mask = (((int)hbyte) & 0xff) << 8 | (((int)lbyte) & 0xff);
That would combine two together (post by Laurence Gonsalves from another post) but I can't figure out the syntax to get four together.
Or would this be case for an Enumset, which I'll admit I don't fully understand.
Any advice would be appreciated.
Thanks.
Tony
**Just to add another quick note to this, (I'm not sure if that's generally allowed so I apologise in advance if it's not), what is the best way of going through my newly created int and checking if a bit is set or not?
Currently I'm usingif (((comboOfBytes >> bitmaskBit) & 1) == 0)
but I don't know if that's the most elegant way of doing the check that I need.
Also I'm still not entirely sure if I understand how shifting actually allows all 32 bits to be checked!
Thanks again
You can use a DataInputStream
to read 4 bytes as an int from your file.
Alternately, if you read bytes a, b, c, d:
int comboOfBytes = ((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff);
The (& 0xff) is necessary to prevent sign bit extension from clobbering higher bytes.