简体   繁体   中英

Store 3 last bits of each byte in a byte array to new byte array

I have a byte array: byte[] test= new byte[100]; I want to read 3 bits of each byte in array test and store in a new array (eg: byte[] result ) Could you please show me the best way?

byte[] test= new byte[15];
    test[0]=0;
    test[1]=1;
    test[2]=2;
    test[3]=3;
    test[4]=4;
    test[5]=5;
    test[6]=6;
    test[7]=7;
    test[8]=8;
    test[9]=9;
    test[10]=10;
    test[11]=11;
    test[12]=12;
    test[13]=13;
    test[14]=14;

    byte[] bitSet = new byte[8];
    int offset =0;
    int result = 0;
    while (offset < test.length){
    for (int i = 0; i < bitSet.length; i++) {

            bitSet[i] =  (byte) (test[offset] & 7 ); 
            System.out.println(bitSet[i]);
            offset++;

        }   
    }
    result = ((bitSet[0] << 7) + (bitSet[1] << 6) + (bitSet[2] << 5) + (bitSet[3] << 4) + (bitSet[4] << 3)
            + (bitSet[5] << 2) + (bitSet[6] << 1) + (bitSet[7] << 0));

    System.out.print(result);

I have tried the code above but it's failed at line bitSet[i] = (byte) (test[offset] & 7 ); . Could some body take a look! I'm really new in programming

A for loop will do the trick

for (int i = 0; i < test.length; i++) {
    result[i] = test[i] & 7; // get the 3 lower bits, use whatever "mask" you need
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM