bitwise OR (on array)

て烟熏妆下的殇ゞ 提交于 2019-12-03 01:02:46

问题


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 information i.e bitwise OR of a and b */

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/16933592/bitwise-or-on-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!