isNaN1247
isNaN1247

Reputation: 18099

Variation between C# and Java when converting long to byte array

I'm not experienced in Java and so this is going straight over my head:-

Java Code:

long foo = 1234567890;
byte[] boo = ByteBuffer.allocate(8).putLong(foo).array();

C# Code:

long foo = 1234567890;
byte[] bar = BitConverter.GetBytes(foo);

// reverse to match Java's Big Endianess
byte[] boo = bar.Reverse().ToArray();

In the Java sample, boo = 0, 0, 0, 0, 73, -106, 2, -46

However in C#, boo = 0, 0, 0, 0, 73, 150, 2, 210

Can someone with a bigger brain, explain why these differ?

Many thanks!

Upvotes: 1

Views: 1030

Answers (1)

David Yaw
David Yaw

Reputation: 27864

Java is using signed bytes, C# is using unsigned. Note that all values < 127 match, and values > 128 are converted to a negative number. If you converted the C# array from byte to sbyte, the values would match.

Upvotes: 12

Related Questions