Search code examples
javaarraysbytebit-manipulationbitwise-and

How to AND byte array in Java?


So I was wondering if/how one might use the AND operation on a byte array in Java?

I've seen samples of how to use the AND operation with ints like so:

int bitmask = 0x000F;
int val = 0x2222;

// prints "2"
System.out.println(val & bitmask);

But say I have a byte Array like...

byte[] byteArray = new byte[1];

and I want to AND it so that I remove the leftmost/fist bit in the array. I figure I'd use the mask 0x7F but how would I AND that with the byte array?


Solution

  • I want to AND it so that I remove the leftmost/fist bit in the array

    I assume with remove you mean unset, because you can't remove the first bit. It will always be there. If I am right, you can do this:

        byteArray[0] &= 127;