2

I am trying to use BitConverter to convert byte arrays to Integers so I can perform bitwise operations on the entire array. However, it appears my machine deals with bytes as little endian, but I have some static values that are in big endian.

I am able to deal with it by reversing the arrays if BitConverter.IsLittleEndian, but I'm wondering if there is a way to force the BitConverter class to use a specific endianess instead (without creating my own class, I'm looking for an existing method).

What I'm doing now:

Dim MyBytes() as Byte = New Byte() { 0, 0, 0, 1 }
Dim MyBytesAsInteger as Integer
If BitConverter.IsLittleEndian Then
    MyBytesAsInteger = BitConverter.ToInt32(MyBytes.Reverse.ToArray, 0)
Else
    MyBytesAsInteger = BitConverter.ToInt32(MyBytes, 0)
End If
yitzih
  • 3,018
  • 3
  • 27
  • 44
  • `but I'm wondering if there is a way` - probably not, as `BitConverter` appears to be designed to [respect the endiannes of the current machine](https://stackoverflow.com/a/2021679/11683), but there are [workarounds](https://stackoverflow.com/q/8241060/11683). – GSerg Oct 31 '17 at 17:04
  • you know you are creating a byte array not bit array. 1 byte=8 bits so you have an array of 4 integer of 8 bit and not an array of 4 bits –  Oct 31 '17 at 21:39
  • 1
    @MutedDisk : The OP never implied that he was dealing with bits? Note that the [**`BitConverter` class**](https://msdn.microsoft.com/en-us/library/system.bitconverter(v=vs.110).aspx) doesn't actually work with bits, but with bytes. So it's Microsoft that has given the class an incorrect name. :p – Visual Vincent Oct 31 '17 at 23:23

1 Answers1

3

I've just found a piece of code that can handle Big/Little endian conversions, made by Jon Skeet.

https://jonskeet.uk/csharp/miscutil/ (download the sources from here)

His library has many utility functions. For Big/Little endian conversions you can check the MiscUtil/Conversion/EndianBitConverter.cs file.

var littleEndianBitConverter = new MiscUtil.Conversion.LittleEndianBitConverter();
littleEndianBitConverter.ToInt64(bytes, offset);

var bigEndianBitConverter = new MiscUtil.Conversion.BigEndianBitConverter();
bigEndianBitConverter.ToInt64(bytes, offset);

His software is from 2009 but I guess it's still relevant.

Endel Dreyer
  • 1,644
  • 18
  • 27