ByteBuffer.wrap().getInt() equivalent in c#

917 Views Asked by At

Java

byte[] input = new byte[] { 83, 77, 45, 71, 57, 51, 53, 70 };

int buff = ByteBuffer.wrap(input).getInt();

Output: 1397566791

C#

byte [] array = { 83, 77, 45, 71, 57, 51, 53, 70 };

MemoryStream stream = new MemoryStream();
using (BinaryWriter writer = new BinaryWriter(stream))
{
     writer.Write(array);
}
byte[] bytes = stream.ToArray();

int buff = BitConverter.ToInt32(bytes, 0);

Output: 1194151251

I have no idea how to get the same output

Thanks

2

There are 2 best solutions below

1
On BEST ANSWER

Well, Int32 consists of 4 bytes only, let's Take them with the help of Take(4). Next, we have to take ending (Big or Little) into account and Reverse these 4 bytes if necessary:

  using System.Linq;

  ... 

  byte[] array = { 83, 77, 45, 71, 57, 51, 53, 70 };
        
  // 1397566791
  int buff = BitConverter.ToInt32(BitConverter.IsLittleEndian 
    ? array.Take(4).Reverse().ToArray()
    : array.Take(4).ToArray());
1
On

In the Java case, it's taking the first 4 bytes in order and converting them to an int.

System.out.println((((((83<<8)+77)<<8)+45)<<8)+71);
1397566791

In C# it is taking the first four in reverse order.

System.out.println((((((71<<8)+45)<<8)+77)<<8)+83);
1194151251

So you need to read the API documentation that describes the operation for both classes and use them accordingly. There should be a way to reverse the byte order.

To go from C# to Java it would be something like this.

buff = ByteBuffer.wrap(input).order(ByteOrder.LITTLE_ENDIAN).getInt();
System.out.println(buff);

Prints

1194151251