yitzih
yitzih

Reputation: 3118

For BitConverter To Use Big Endian

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

Upvotes: 2

Views: 6925

Answers (1)

Endel Dreyer
Endel Dreyer

Reputation: 1654

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.

Upvotes: 3

Related Questions