I am trying to send an array of byte representing an integer from a c# ASP.Net page to a java client as follows
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);
}
and on java side
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;
}
These procedures work correctly for integers less than 128 but for 128 the java side returns 239. I know that the issue is related to the fact that java memory storage is Big – Endians Signed Bytes while .Net C# is Little – Endians Unsigned Bytes. I’m also aware of the following posts
Get int from bytes in Java, encoded first in C#
different results when converting int to byte array - .NET vs Java
Java and C# - byte array to long conversion difference
however I cannot change the java side as the above posts suggest. I have to modify C# side to suit other end.
How may I do that?
[UPDATED]
I changed the C# side based on MiscUtil as follows
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);
}
however the result has not changed. Java still returns 239 (while expecting 128)
Why? and how may I correct it?