Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte order java/.net

Tags:

java

c#

sockets

When sending information from a java application to a C# application through sockets, is the byte order different? Or can I just send an integer from C# to a java application and read it as integer?

(And do the OS matter, or is the same for java/.net no matter how the actual OS handles it?)

like image 682
jgauffin Avatar asked Dec 10 '22 08:12

jgauffin


1 Answers

It all comes down to how you encode the data. If you are treating it only as a raw sequence of bytes, there is no conflict; the sequence is the same. When the matters is in endianness when interpreting chunks of the data as (for example) integers.

Any serializer written with portability in mind will have defined endianness - for example, in protocol buffers (available for both Java and C#) little-endian is always used regardless of your local hardware.

If you are doing manual writing to the stream, using things like shift-based encoding (rather than direct memory copying) will give you defined endianness.

If you use pre-canned platform serializers, you are at the mercy of the implementation. It might be endian-safe, it might not be (i.e. it might depend on the platform at both ends). For example, the .NET BitConverter class is not safe - it is usually assumed (incorrectly) to be little-endian, but on some platforms (and particularly in Mono on some hardware) it could be big-endian; hence the .IsLittleEndian property.

My advice would be to use a serializer that handles it all for you ;p

like image 80
Marc Gravell Avatar answered Dec 11 '22 22:12

Marc Gravell