在 C# 中如何获取两个字节并将它们组合成一个 UInt16?

发布于 2024-09-24 12:53:50 字数 275 浏览 1 评论 0原文

我想要一个带有主体的方法:

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

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

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

I want to have a method with the body:

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

So, I want to get the value at memory[address] AND the next byte and combine them into a single UInt16.

For the order of the bytes, the machine I'm implementing is little endian if that matters. How do I get both of those byte values and combine them into a single UInt16 in C#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

以歌曲疗慰 2024-10-01 12:53:50

一种方法是使用 BitConverter< /a> class:

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

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

One way is to use the BitConverter class:

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

This will interpret the bytes according to the native endianness on the machine.

夏日浅笑〃 2024-10-01 12:53:50

使用位移位:

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

您可以使用 BitConverter 类,但要注意有一个名为 IsLittleEndian 的静态只读字段使用前应检查。如果它已经设置为小端,那么您可以使用此类,但如果它设置为错误的值,您将无法修改它。

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

Use a bitshift:

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

You could use the BitConverter class but be aware that there is a static readonly field called IsLittleEndian that you should check before using it. If it already set to little endian then you can use this class, but if it is set to the wrong value you cannot modify it.

Alternatively you could take a look at Jon Skeet's MiscUtil library which includes as EndianBitConverter class that allows you to specify the endianness.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文