【问题标题】:Getting High/ Low Byte from ushort results in incorrect result从 ushort 获取高/低字节会导致结果不正确
【发布时间】:2019-05-06 17:17:46
【问题描述】:

所以我目前正在编写一个库,它将帮助我通过 USB 端口this 与指纹扫描仪进行接口,事实上,它只是转售的 Zhiantec(文档 here)。

所以我遇到的问题是:文档指定标头字节、标头、包长度和校验和字节首先传输高字节。没什么大不了的,在快速谷歌之后,我找到了 Jon Skeet 的this 答案,显示了如何做到这一点。然后我把它放到两个看起来像这样的小辅助方法中:

public static class ByteHelper
{
    // Low/ High byte arithmetic
    // byte upper = (byte) (number >> 8);
    // byte lower = (byte) (number & 0xff);

    public static byte[] GetBytesOrderedLowHigh(ushort toBytes)
    {
        return new[] {(byte) (toBytes & 0xFF), (byte) (toBytes >> 8)};
    }

    public static byte[] GetBytesOrderedHighLow(ushort toBytes)
    {
        return new[] {(byte) (toBytes >> 8), (byte) (toBytes & 0xFF)};
    }
}

我正在测试,看看他们是否使用此代码做正确的事情:

// Expected Output '0A-00', actual '00-0A'
Console.WriteLine(BitConverter.ToString(ByteHelper.GetBytesOrderedHighLow(10)));

// Expected Output '00-0A', actual '0A-00'
Console.WriteLine(BitConverter.ToString(ByteHelper.GetBytesOrderedLowHigh(10)));

但是我得到了错误的输出(参见上面的 Console.WriteLine 语句的 cmets),谁能解释我为什么这样做以及如何解决它?

【问题讨论】:

  • “为什么这样做” - 了解字节序。您可能只想反转数组。
  • 你确定你没有混淆方法名吗?
  • @Vasek 我没有混淆方法名(你可以在测试代码中检查自己)
  • 我查过了。一切正常。
  • @CodeCaster 谢谢你的提示,一定会读到的

标签: c# bitwise-operators


【解决方案1】:

你得到的结果是正确的。

您的LowHigh-方法切换两个字节。

00-0A 将是 0A-00

您的HighLow-方法仅将ushort 转换为字节数组。

00-0A 将保持 00-0A

这里是您的逻辑的分步示例,还有更多输出以便更好地理解:

ulong x = 0x0A0B0C;
Console.WriteLine(x.ToString("X6"));
// We're only interested in last 2 Bytes:
ulong x2 = x & 0xFFFF;

// Now let's get those last 2 bytes:
byte upperByte = (byte)(x2 >> 8); // Shift 8 bytes -> tell get dropped
Console.WriteLine(upperByte.ToString("X2"));
byte lowerByte = (byte)(x2 & 0xFF); // Only last Byte is left
Console.WriteLine(lowerByte.ToString("X2"));

// The question is: What do you want to do with it? Switch or leave it in this order?

// leave them in the current order:
Console.WriteLine(BitConverter.ToString(new byte[] { upperByte, lowerByte }));

// switch positions:
Console.WriteLine(BitConverter.ToString(new byte[] { lowerByte, upperByte }));

【讨论】:

  • 你完全正确。我误解了高/低字节的定义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 2012-03-18
  • 1970-01-01
相关资源
最近更新 更多