bitwise OR (on array)

后端 未结 2 625
无人及你
无人及你 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;
    }
    
    0 讨论(0)
  • 2021-01-29 12:17

    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;
    }
    
    0 讨论(0)
提交回复
热议问题