0

I have this python code:

f = open('file.bin', 'rb')
b = f.read(2)
bytes = b[0x0:0x2] //this is b'\x10\x24', for example
f.close()
a = int.from_bytes(bytes, 'big') //returns 4132

I can't seem to figure out how to achieve the same thing in C#.

Did find this method:

public static int IntFromBigEndianBytes(byte[] data, int startIndex = 0)
    {
      return (data[startIndex] << 24) | (data[startIndex + 1] << 16) | (data[startIndex + 2] << 8) | data[startIndex + 3];
    }

Trying that method always results in an IndexOutOfRangeException because my input bytes are less than 4. An insight to why this is happening, or otherwise any information would be appreciated.

ZeroSkill
  • 47
  • 5

1 Answers1

0

Disregarding any other problem. There are many ways to do this, essentially what you are asking is how to take a byte array that represent a 16 bit value (short,Int16) and assign it to an int

Given

public static int IntFromBigEndianBytes(byte[] data) 
    => (data[0] << 8) | data[1];

public static int IntFromBigEndianBytes2(byte[] data) 
    => BitConverter.ToInt16(data.Reverse().ToArray());

Usage

var someArray = new byte[]{0x10, 0x24};

Console.WriteLine(IntFromBigEndianBytes(someArray));
Console.WriteLine(IntFromBigEndianBytes2(someArray));

Output

4132
4132

Full Demo Here

Note you should also be using BitConverter.IsLittleEndian == false to determine the endianness of your system with these methods, and reverse the logic on a big endian architecture

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • This is great, thank you. However, `Convert.ToInt32(array.Hex()), 16);` also did the trick, where `.Hex()` turns the bytes into a hex string. – ZeroSkill Oct 05 '20 at 12:30