bitwise OR (on array)

后端 未结 2 632
无人及你
无人及你 2021-01-29 11:16

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         


        
2条回答
  •  庸人自扰
    2021-01-29 12:16

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

提交回复
热议问题