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

Tags: , , , ,



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

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());


Source: stackoverflow