Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending double with tcp from java to C#

I have a Java SocketServer that sends doubles to a C# client. The sever sends the doubles with DataOutputStream.writeDouble() and the client reads the double with BinaryReader.ReadDouble(). When I send dos.writeDouble(0.123456789); and flush it from the server the client reads and outputs 3.1463026401691E+151 which is different from what I sent. Are the C# and Java doubles each encoded differently?

like image 825
Orangelight Avatar asked Jun 18 '15 00:06

Orangelight


1 Answers

In Java, DataOutputStream.writeDouble() converts the double to a long before sending, writing it High byte first (Big endian).

However, C#, BinaryReader.ReadDouble() reads in Little Endian Format.

In other words: The byte order is different, and changing one of them should fix your problem.

The easiest way to change the byte order in Java from Big to Little Endian is to use a ByteBuffer, where you can specify the endian type: eg:

ByteBuffer buffer = ByteBuffer.allocate(yourvaluehere); 
buffer.order(ByteOrder.LITTLE_ENDIAN); 
// add stuff to the buffer
byte[] bytes = buffer.array();

Then, use DataOutputStream.write()

like image 189
Aify Avatar answered Oct 31 '22 05:10

Aify