Byte array to String and back.. issues with -127

前端 未结 4 1753
野的像风
野的像风 2020-12-08 14:20

In the following:

 scala> (new String(Array[Byte](1, 2, 3, -1, -2, -127))).getBytes
 res12: Array[Byte] = Array(1, 2, 3, -1, -2, 63)

why

4条回答
  •  一个人的身影
    2020-12-08 14:46

    String is for storing text not binary data.

    In your default character encoding there is no charcter for -127 so it replaces it with '?' or 63.

    EDIT: Base64 is the best option, even better would be to not use text to store binary data. It can be done, but not with any standard character encoding. i.e. you have to do the encoding yourself.

    To answer your question literally, you can use your own character encoding. This is a very bad idea as any text is likely to get encoded and mangled in the same way as you have seen. Using Base64 avoids this by using characters which are safe in any encoding.

    byte[] bytes = new byte[256];
    for (int i = 0; i < bytes.length; i++)
        bytes[i] = (byte) i;
    String text = new String(bytes, 0);
    byte[] bytes2 = new byte[text.length()];
    for (int i = 0; i < bytes2.length; i++)
        bytes2[i] = (byte) text.charAt(i);
    int count = 0;
    for (int i = 0; i < bytes2.length; i++)
        if (bytes2[i] != (byte) i)
            System.out.println(i);
        else
            count++;
    System.out.println(count + " bytes matched.");
    

提交回复
热议问题