gpt4 book ai didi

java - getBytes() 方法返回未知字节

转载 作者:行者123 更新时间:2023-12-02 03:30:04 24 4
gpt4 key购买 nike



import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class Main {
public static void main(String[] args)
{
try
{
String s = "s";
System.out.println( Arrays.toString( s.getBytes("utf8") ) );
System.out.println( Arrays.toString( s.getBytes("utf16") ) );
System.out.println( Arrays.toString( s.getBytes("utf32") ) );
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}

控制台:


[115]
[-2, -1, 0, 115]
[0, 0, 0, 115]

这是什么?

[-2, -1] - ???

另外,我注意到,如果我这样做:


String s = new String(new char[]{'\u1251'});
System.out.println( Arrays.toString( s.getBytes("utf8") ) );
System.out.println( Arrays.toString( s.getBytes("utf16") ) );
System.out.println( Arrays.toString( s.getBytes("utf32") ) );

控制台:


[-31, -119, -111]
[-2, -1, 18, 81]
[0, 0, 18, 81]

最佳答案

不要忘记 Java 中的字节是无符号的。所以-2、-1实际上意味着0xfe 0xff...而U+FEFF是Unicode byte order mark (BOM)...这就是您在 UTF-16 版本中看到的内容。

为避免在编码时获取 BOM,请显式使用 UTF-16BE 或 UTF-16LE。 (我还建议使用 names which are guaranteed by the platform 而不仅仅是“utf8”等。诚然,该名称保证在不区分大小写的情况下找到,但缺少连字符使其不太可靠,并且使用规范没有任何缺点名称。)

关于java - getBytes() 方法返回未知字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56890201/

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