Is there a compact way to encode binary data in Java?

I can do it in java

final byte[] b = new byte[]{0x01, 0x02, 0x04, 0x08,
                            (byte)0x80, 0x40, 0x20, (byte)0xff,
                            (byte)0xef, 0x40, 0x30, (byte)0xfe,
                            0x3f, (byte)0x90, 0x44, 0x78};

whereas in Python 2.x I can just use

b = '\x01\x02\x04\x08\x80\x40\x20\xff\xef\x40\x30\xfe\x3f\x90\x44\x78'

Java syntax is a pain and requires the (byte)processing of values ​​with the most significant set of bits.

Is there an easier way? (other than writing a helper class to include a string like "01020408804020ffef4030fe3f904478", in byte[])

+4
source share
1 answer

Choose your poison. All alternatives are somehow painful.
It is regrettable that the Java type is bytesigned instead of unsigned .

  • - . . .

    byte[] b = {(byte)0x00, (byte)0x7F, (byte)0x80, (byte)0xFF};
    
  • -, . . , .

    byte[] b = {0, 127, -128, -1};
    
  • . .

    byte[] b = toBytes(new int[]{0x00, 0x7F, 0x80, 0xFF});
    
    static byte[] toBytes(int[] x) {
        byte[] y = new byte[x.length];
        for (int i = 0; i < x.length; i++)
            y[i] = (byte)x[i];
        return y;
    }
    
  • . 2 ( 0x) .

    byte[] b = hexToBytes("007F80FF");
    
    static byte[] hexToBytes(String s) {
        byte[] b = new byte[s.length() / 2];
        for (int i = 0; i < b.length; i++)
            b[i] = (byte)Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);
        return b;
    }
    
  • Base64. , # 4, . java.util.Base64 (Java SE 8+). , blob- Base64 Java.

+3

All Articles