Run Code  | API  | Code Wall  | Misc  | Feedback  | Login  | Theme  | Privacy  | Patreon 

Decode byte array

//'main' method must be in a class 'Rextester'.
//Compiler version 1.8.0_111

import java.util.*;
import java.lang.*;

class Rextester
{  
    public static void main(String args[])
    {
        System.out.println(parseByteArray(new byte[] {
            (byte) 0xff, 
            (byte) 0x40, (byte) 0x1,
            (byte) 0x20, (byte) 0x1, (byte) 0x0,
            (byte) 0x10, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0
        }).toString());
    }
    
    public static List<Integer> parseByteArray(byte[] input) {
        List<Integer> res = new ArrayList<>();
        int n = input.length;
        if (n == 0) return res;
        for (int i = 0; i < n;) {
            int len = 1, val = 0;
            if (input[i] < 0) {
                len = 1;
                val = input[i] & 0x7f;
            } else if ((input[i] & 0b1100_0000) == 0b0100_0000) {
                len = 2;
                val = input[i] & 0x3f;
            } else if ((input[i] & 0b1110_0000) == 0b0010_0000) {
                len = 3;
                val = input[i] & 0x1f;
            } else if ((input[i] & 0xf0) == 0x10) {
                len = 4;
                val = input[i] & 0xf;
            }
            System.out.println(len);
            for (int j = i + 1; j < i + len; j++) {
                val <<= 8;
                val |= (input[j] & 0xff);
            }
            System.out.println(Integer.toBinaryString(val));
            res.add(val);
            i += len;
        }
        return res;
    }
}
 run  | edit  | history  | help 0