I need to perform bitwise OR of two arrays of byte in Java. How can I do so?
byte a= new byte[256];
byte b= new byte[256];
byte c; /*it should contain informati
I think your best bet is to use a BitSet
.
That class already has a void or(BitSet bs)
method to use.
byte a = new byte[256];
byte b = new byte[256];
byte c = new byte[256];
BitSet bsa = new BitSet();
BitSet bsa = new BitSet();
//fill BitSets with values from your byte-Arrays
for(int i = 0; i < a.length * 8; i++)
if((a[i/8] & (1 << 7-i%8)) != 0)
bsa.set(i);
for(int i = 0; i < a.length * 8; i++)
if((b[i/8] & (1 << 7-i%8)) != 0)
bsb.set(i);
//perform OR
bsa.or(bsb);
//write bsa to byte-Array c
for(int i = 0, byte h; i < a.length; i++){
h = 0;
for(int j = 7; j >= 0; j++){
if(bsa.get(i*8 + 7 - j))
h = h | (1 << j);
}
c[i] = h;
}
Thats as simple as using the | operator and a loop:
public static byte[] byteOr(byte[] a, byte[] b) {
int len = Math.min(a.length, b.length);
byte[] result = new byte[len];
for (int i=0; i<len; ++i)
result[i] = (byte) (a[i] | b[i])
return result;
}