如何在C#中将两个字节合并为一个UInt16?

时间:2010-09-21 20:19:57

标签: c# .net bit-manipulation

我想要一个身体的方法:

public UInt16 ReadMemory16(Byte[] memory, UInt16 address)
{
    // read two bytes at the predefined address
}

所以,我想获取内存[地址]和下一个字节的值,并将它们组合成一个UInt16。

对于字节的顺序,如果重要的话,我正在实现的机器是小端。如何获取这两个字节值并将它们组合到C#中的单个UInt16中?

3 个答案:

答案 0 :(得分:13)

一种方法是使用BitConverter类:

public UInt16 ReadMemory16(Byte[] memory, UInt16 address)
{
    return System.BitConverter.ToUInt16(memory, address);
}

这将根据计算机上的本机字节顺序解释字节。

答案 1 :(得分:8)

使用bitshift:

return (ushort)((memory[address + 1] << 8) + memory[address]);

您可以使用BitConverter类,但请注意,在使用之前应该检查一个名为IsLittleEndian的静态只读字段。如果它已设置为little endian,那么你可以使用这个类,但是如果设置为错误的值你就无法修改它。

或者您可以查看Jon Skeet的MiscUtil库,其中包含EndianBitConverter类,允许您指定字节序。

答案 2 :(得分:1)