简体   繁体   中英

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...

C# code:

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

Java code:

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

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

As the bytes in the stream were encoded using some encoding, you must explicitly set the correct encoding in your C# and Java code.

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. Or exchange the encoding type somewhere in the stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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