3

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?

1
  • 4
    You can't AND it as a whole, but you can go one by one: byteArray[0] &= 0x7F. Commented Jun 28, 2013 at 21:53

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.