gpt4 book ai didi

Java byte[] 到/从 String 转换

转载 作者:搜寻专家 更新时间:2023-10-31 20:03:46 25 4
gpt4 key购买 nike

为什么这个 junit 测试失败了?

import org.junit.Assert;
import org.junit.Test;

import java.io.UnsupportedEncodingException;

public class TestBytes {
@Test
public void testBytes() throws UnsupportedEncodingException {
byte[] bytes = new byte[]{0, -121, -80, 116, -62};
String string = new String(bytes, "UTF-8");
byte[] bytes2 = string.getBytes("UTF-8");
System.out.print("bytes2: [");
for (byte b : bytes2) System.out.print(b + ", ");
System.out.print("]\n");
Assert.assertArrayEquals(bytes, bytes2);
}
}

我会假设传入的字节数组等于结果,但不知何故,可能由于 UTF-8 字符占用两个字节这一事实,结果数组在内容和长度上都与传入数组不同。

请赐教。

最佳答案

原因是 0, -121, -80, 116, -62 不是有效的 UTF-8 字节序列。 new String(bytes, "UTF-8") 在这种情况下不会抛出任何异常,但结果很难预测。阅读http://en.wikipedia.org/wiki/UTF-8 无效的字节序列部分。

关于Java byte[] 到/从 String 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16232023/

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