对于BitConverter使用Big Endian

问题描述 投票:0回答:1

我试图使用BitConverter将字节数组转换为整数,这样我就可以对整个数组执行按位运算。但是,看起来我的机器处理字节为小端,但我有一些大端的静态值。

我可以通过反转数组来处理它,如果BitConverter.IsLittleEndian,但我想知道是否有办法强制BitConverter类使用特定的endianess而不是创建我自己的类,我正在寻找一个现有的方法)。

我现在在做什么:

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
.net vb.net endianness
1个回答
0
投票

我刚刚找到了一段可以处理由Jon Skeet制作的Big / Little端转换的代码。

https://jonskeet.uk/csharp/miscutil/(从这里下载资源)

他的图书馆有许多实用功能。对于Big / Little端转换,您可以查看MiscUtil/Conversion/EndianBitConverter.cs文件。

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

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

他的软件是从2009年开始的,但我想这仍然是相关的。

© www.soinside.com 2019 - 2024. All rights reserved.