我正在尝试将表示整数的字节数组从 ac# ASP.Net 页面发送到 java 客户端,如下所示
public void WriteToStream(int i)
{
byte[] buffer = BitConverter.GetBytes(i);
var writer = new MemoryStream();
// Little - Endians to Big - Endians;
Array.Reverse(buffer);
// Unsigned Char to Signed Char
sbyte[] suffer = (sbyte[])(Array)buffer;
BinaryWriter binaryWriter = new BinaryWriter(writer);
foreach (var sb in suffer)
{
binaryWriter.Write(sb);
}
binaryWriter.Close();
buffer = writer.ToArray();
writer.Close();
// Writing to an Aspx Page Response Output Stream
Response.OutputStream.Write(buffer, 0, buffer.Length);
}
在java方面
public int getInt(byte[] data)
{
byte[] buffer;
ByteArrayInputStream reader = new ByteArrayInputStream(data);
buffer = new byte[4];
reader.read(buffer, 0, 4);
int i = ByteBuffer.wrap(buffer).getInt();
return i;
}
这些过程对于小于128的整数正常工作,但对于128,java 端返回239。我知道这个问题与 java 内存存储是Big – Endians Signed Bytes而 .Net C# 是Little – Endians Unsigned Bytes的事实有关。我也知道以下帖子
将 int 转换为字节数组时的不同结果 - .NET 与 Java
但是我不能像上面的帖子所建议的那样改变java端。我必须修改 C# 端以适应另一端。
我该怎么做?
[更新]
我基于MiscUtil更改了 C# 端如下
public void WriteToStream(int i)
{
var stream = new MemoryStream();
var writer = new EndianBinaryWriter(EndianBitConverter.Big, stream);
writer.Write(i);
byte[] buffer = stream.ToArray();
// Writing to an Aspx Page Response Output Stream
Response.OutputStream.Write(buffer, 0, buffer.Length);
}
但是结果没有改变。Java 仍然返回239(同时期望128)
为什么?我该如何纠正?