简体   繁体   English

Java 字符串结果与 C# 不同

[英]Java string results different to C#

I'm reading a socket stream and converting the byte array to a single string in both Java & C#, but the results are different...我正在读取一个套接字 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 并将字节数组转换为 Java 和 C# 中的单个字符串,但结果不同......

C# code: C# 代码:

string text = Encoding.Default.GetString(ms.ToArray());

Java code: Java代码:

String text = new String(data);

One of the potential issues I encountered upon research was that C#'s default encoding was UTF-32 & Java's was UTF8 , as well as C# uses little endian and Java uses Big endian, so the solution would be to define charset in java as UTF-32LE but even then it returns entirely different to C# and most if not all of the string is a combination of One of the potential issues I encountered upon research was that C#'s default encoding was UTF-32 & Java's was UTF8 , as well as C# uses little endian and Java uses Big endian, so the solution would be to define charset in java as UTF-32LE但即便如此,它返回的结果与 完全不同,而且大多数(如果不是全部)字符串都是

Just as extra information regarding my methods in Java I'm using ByteArrayOutputStream to store data from DataInputStream & in C# I'm using MemoryStream to store data from NetworkStream正如有关我在 Java 中的方法的额外信息一样,我正在使用ByteArrayOutputStream来存储来自DataInputStream和 C# 中的数据,我正在使用MemoryStream来存储来自NetworkStream的数据

As the bytes in the stream were encoded using some encoding, you must explicitly set the correct encoding in your C# and Java code.由于 stream 中的字节使用某种编码进行编码,因此您必须在 C# 和 Java 代码中明确设置正确的编码。

They use different default encodings.它们使用不同的默认编码。

To make the byte stream interoperable, you must stick with one encoding which is used to encode string to bytes.要使字节 stream 可互操作,您必须坚持使用一种用于将字符串编码为字节的编码。 Or exchange the encoding type somewhere in the stream.或者在 stream 中某处交换编码类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM