不同的结果转换成int值的字节数组时 - .NET和Java [英] different results when converting int to byte array - .NET vs Java
问题描述
我试图从Java客户端发送数据到C#服务器有问题转换成int值的字节数组。
I am trying to send data from a java client to a c# server and having trouble converting int to byte array.
当我转换数8342与C#使用此代码:
when i am converting the number 8342 with c# using this code:
BitConverter.GetBytes(8342)
结果是:X [4] = {150,32,0,0}
the result is: x[4] = { 150, 32, 0, 0 }
用java我使用
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(8342);
return bb.array();
和这里的结果是:X [4] = {0,0,32,-106}
and here the result is: x[4] = { 0, 0, 32, -106 }
有人能解释一下吗?我是新来的Java,这是我第一次看到字节数组负数
Can someone explain? I am new to java and this is the first time i see negative numbers in byte arrays.
推荐答案
您必须改变字节序:
bb.order(ByteOrder.LITTLE_ENDIAN)
Java的内部存储东西大端,而.NET是Little Endian默认。
Java stores things internally as Big Endian, while .NET is Little Endian by default.
也有在签署差异, Java和.NET之间的无符号。 Java使用符号字节,C#使用无符号。你将不得不改变,以及
Also there is difference in signed and unsigned between Java and .NET. Java uses signed bytes, C# uses unsigned. You will have to change that as well.
基本上,这就是为什么你看到-106(150 - 256)
Basically, that is why you are seeing -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));
}
请注意,值长。
这篇关于不同的结果转换成int值的字节数组时 - .NET和Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!