Question

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?

Was it helpful?

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;

OTHER TIPS

The bitwise and operator would do the trick, it is simply &

This is the demo they present for masking:

class BitDemo {
    public static void main(String[] args) {
        int bitmask = 0x000F;
        int val = 0x2222;
        // prints "2"
        System.out.println(val & bitmask);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top