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?

This 0ne Pr0grammer
  • 2,632
  • 14
  • 57
  • 81

2 Answers2

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);
    }
}
Stephan
  • 16,509
  • 7
  • 35
  • 61
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;
jlordo
  • 37,490
  • 6
  • 58
  • 83