Tony
Tony

Reputation: 3638

Java four bytes to binary 'bitmask'

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

Upvotes: 2

Views: 2806

Answers (4)

Jay
Jay

Reputation: 27474

I don't know the bigger context of what you're up to, but if you control the data structure, if you need 32 flags, I suspect it would be a whole lot easier to just create a boolean[32] array.

Yes, bit flags save memory, but unless you have millions of them, this is probably unimportant.

I'm not saying that there's never a time when an int composed of a bunch of bit flags and then being used to mask a data stream is not a good idea, but I think it is rarely a good idea.

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

An EnumSet is a Set of Enum elements. You probably mean BitSet

Upvotes: 0

Mike Samuel
Mike Samuel

Reputation: 120506

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.

Upvotes: 2

maaartinus
maaartinus

Reputation: 46412

I always use the following

public static int compose(byte x3, byte x2, byte x1, byte x0) {
    return (x3 << 24)
            + ((x2 & 0xFF) << 16)
            + ((x1 & 0xFF) << 8)
            + ((x0  & 0xFF) << 0);
}

However, you may want to use a DataStream instead.

And no, EnumSet is not the way to go. EnumSet is just an efficient implementation of Set specialized for Enums. It has no IO capabilities beyond serialization.

Upvotes: 1

Related Questions