gpt4 book ai didi

Java:不同的byte[]在utf8中具有相同的字符串

转载 作者:行者123 更新时间:2023-12-01 17:47:09 24 4
gpt4 key购买 nike

有两个不同的字节数组。当我从 byte[] 获取字符串时。当我使用 utf8 时,它们具有相同的值。当我使用 ISO-8859-1 时正好相反。

    byte[] valueFir = new byte[]{0, 1, -79};
byte[] valueSec = new byte[]{0, 1, -80};

Charset CHARSET = Charset.forName("ISO-8859-1");
Charset UTF8SET = Charset.forName("UTF-8");
Charset[] list = new Charset[]{CHARSET, UTF8SET};

for(int i=0; i<list.length; i++){

String fir = new String(valueFir,list[i]);
String sec = new String(valueSec,list[i]);

Assert.assertNotEquals(fir,sec);
}

第一个断言为 true,第二个断言为失败。原因是什么?

最佳答案

如果你看Javadoc for the String constructor that you're using ,它说

This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement string.

现在,在 UTF8 中,字节 -79 和 -80 不会映射到单个字符。所以你的两个字节数组在 UTF8 中都没有意义。而且因为它们是不可映射的,所以您只需获得默认的 String 两次。然后,您的 assertNotEquals 会将默认的 String 与其自身进行比较。

但是,您的字节数组在 ISO-8859-1 中非常有意义,并且会转换为两个不同的 String 值。

关于Java:不同的byte[]在utf8中具有相同的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53940004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com