Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write out a C# double and read it in Java?

Tags:

java

c#

double

Is it possible to write out the 8-byte representation of a double number in C#, and then read in those 8 bytes in Java as the same double number that was encoded?

like image 757
Nicholas Hill Avatar asked Dec 02 '25 10:12

Nicholas Hill


1 Answers

Yes, both java and .NET use IEEE-754 representations, although Java may omit some of the flags. The main question here is endianness, and that is trivial to reverse if needed. For example, in .NET you can handle this as:

double value = ...
byte[] bytes = BitConverter.GetBytes(value);

and:

byte[] bytes = ...
double value = BitConverter.ToDouble(bytes);

The endianness determines which byte goes first / last, but switching between them is as simple as reversing the array; for example, if you want "big-endian", then you could convert with:

if(BitConverter.IsLittleEndian) {
    Array.Reverse(bytes);
}

(remembering to do that both when reading and writing)

I'm afraid I don't know the java for the same, but it is definitely fully available - I suspect ByteBuffer.putDouble / ByteBuffer.getDouble would be a good start.

like image 86
Marc Gravell Avatar answered Dec 04 '25 22:12

Marc Gravell