为什么这不会取消两个最重要的位?

时间:2013-01-09 06:13:45

标签: c# serial-port bit-manipulation

我觉得这与BitConverter.ToUInt16 wiorks的方式有关,但我不能为我的生活弄清楚为什么这会给我带来时髦的数据。

我需要忽略端口上的前两位,并将剩余的位转换为16位无符号整数。

我尝试过颠倒阵列,扭转我的面具,做两件事,不同的转换以及各种奇怪的事情。

进来的两个字节是第一个是最重要的。需要取消设置第一个字节中的前两位。

有人能指出我正确的方向吗?

byte[] buffer = new byte[2];
int count = port.Read(buffer, 0, buffer.Length);

Console.WriteLine("0: {0}", BitConverter.ToString(buffer));

ushort value = BitConverter.ToUInt16(buffer, 0);

Console.WriteLine("1: {0}", value);

value = (ushort)(value & 0x3FFF);

Console.WriteLine("2: {0}", value);

以下是使用BitConverter.ToUInt16然后使用0x3FFF掩码进行AND运算时的一些示例数据。

0: 80-00
1: 128
2: 128 <-- this should be 0

0: 80-00
1: 128
2: 128 <-- should be 0

0: 01-00
1: 1
2: 1 <-- should be 1, as it is

0: 80-00
1: 128
2: 128 <-- should be 0

0: 80-00
1: 128
2: 128 <-- should be 0

反转数组给我这样的数据:

0: 00-01
1: 256
2: 256 <-- should be 1

0: 01-80
1: 32769
2: 1 <- not sure what this should be, probably 1 though

2 个答案:

答案 0 :(得分:1)

  

进来的两个字节是第一个最重要的字节。

这就是问题所在。 BitConverter.ToUInt16将第一个字节视为最不重要的字节,因为这就是系统的工作方式。请参阅BitConverter.IsLittleEndian

  

我试过反转数组,

那应该有用。或者,手动组合两个字节,而不使用BitConverter

答案 1 :(得分:0)

这样人们就可以获得串口读取和转换14位无符号大端整数的完整代码。

private static void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = sender as SerialPort;
    if (port.BytesToRead < sizeof(ushort))
    {
        return;
    }

    byte[] buffer = new byte[2];
    int count = port.Read(buffer, 0, buffer.Length);

    ushort value = (ushort)(((buffer[0] << 8) | buffer[1]) & 0x3FFF);
    Console.WriteLine(value);
}