简体   繁体   English

将int转换为字节数组时的不同结果 - .NET vs Java

[英]different results when converting int to byte array - .NET vs Java

I am trying to send data from a java client to ac# server and having trouble converting int to byte array. 我试图将数据从java客户端发送到ac#server并且无法将int转换为字节数组。

when i am converting the number 8342 with c# using this code: 当我使用此代码使用c#转换数字8342时:

BitConverter.GetBytes(8342)

the result is: x[4] = { 150, 32, 0, 0 } 结果是:x [4] = {150,32,0,0}

with java i use: 用java我用:

ByteBuffer bb = ByteBuffer.allocate(4); 
bb.putInt(8342); 
return bb.array();

and here the result is: x[4] = { 0, 0, 32, -106 } 这里的结果是:x [4] = {0,0,32,-106}

Can someone explain? 谁能解释一下? I am new to java and this is the first time i see negative numbers in byte arrays. 我是java新手,这是我第一次在字节数组中看到负数。

You have to change endianess: 你必须改变endianess:

 bb.order(ByteOrder.LITTLE_ENDIAN)

Java stores things internally as Big Endian, while .NET is Little Endian by default. Java将内部存储为Big Endian,而.NET默认为Little Endian。

Also there is difference in signed and unsigned between Java and .NET. Java和.NET之间的签名和无符号也有区别。 Java uses signed bytes, C# uses unsigned. Java使用带符号的字节,C#使用无符号。 You will have to change that as well. 你也必须改变它。

Basically, that is why you are seeing -106 ( 150 - 256 ) 基本上,这就是为什么你看到-106(150 - 256)

You will have to do something like the utility method below: 您必须执行以下实用程序方法:

public static void putUnsignedInt (ByteBuffer bb, long value)
    {
       bb.putInt ((int)(value & 0xffffffffL));
    }

Note that value is long. 请注意,值很长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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