【发布时间】:2019-12-16 23:39:48
【问题描述】:
我正在使用InputStream 将字节从 TCP 服务器(用 C# 编写)读取到 byte[],并使用 new String(byteArray, "UTF-16LE") 将它们编码为字符串。此方法对基本多语言平面中的字符进行了很好的编码,但不处理补充字符。
我知道 C# 中的字节是无符号的,而 Java 字节是有符号的,并且补充字符可以由一个或两个 unicode 值组成。
ByteBuffer wrapped = ByteBuffer.wrap(dataBytes);
wrapped.order(ByteOrder.LITTLE_ENDIAN);
short noOfSites = wrapped.getShort();
for(int i = 0; i < noOfSites; i++){
short siteNo = wrapped.getShort();
short textLength = wrapped.getShort();
byte[] textBytes = new byte[textLength];
wrapped.get(textBytes, 0, textLength);
for(byte bite : textBytes){
System.out.print(bite+" ");
} //just to see what's in the byte array
String siteText = new String(textBytes, "UTF_16LE");
System.out.println(siteNo + ": " + siteText);
siteList.add(new Site(siteNo, siteText));
publishProgress(siteNo + " - " + siteText);
}
在本例中,dataBytes 是包含从服务器读取的字节的字节数组,noOfSites 是要从服务器读取的对象数,siteNo 是 ID,textLength 是数字包含站点名称的字节数,textBytes 是保存这些字节的数组。
当从服务器接收到单词“MÜNSTER”时,读入缓冲区的字节为:
77 0 -3 -1 78 0 83 0 84 0 69 0 82 0。
但是,“Ü”字符无法识别,我认为这归因于 Java 尝试(并且失败)编码的 -3 -1 UTF-16 值。我知道在 C# 中,“Ü”由 DC-00 表示,但我不明白为什么这在 Java 中变成 -3 -1。
任何帮助将不胜感激。
【问题讨论】: