【问题标题】:Why I can't convert a byte[2] array to int with BitConverter?为什么我不能使用 BitConverter 将 byte[2] 数组转换为 int?
【发布时间】:2014-07-22 00:36:47
【问题描述】:

主要问题是我从 SerialPort 接收到一个仅使用 10 位的二进制数,所以我用它来接收完整的数据:

byte[] buf = new byte[2];
serialPort.Read(buf, 0, buf.Length);
BitArray bits = new BitArray(buf);

将二进制转换为整数的最初想法是这样的:

foreach (bool b in bits)
{
    if(b){
        binary += "1";
    }
    else{
        binary+= "0";
    }
}

decimal = Convert.ToInt32(binary, 2); 
decimal = decimal >> 6;

binary 显然是一个字符串,它可以工作,但我需要知道是否存在另一个解决方案,而不是我尝试使用的 previuos 代码:

decimal = BitConverter.ToInt16(buf, 0);

但这只能读取前 8 位,我需要缺少其他 2 位!如果我将 ToInt16 更改为 ToInt32

decimal = BitConverter.ToInt32(buf, 0);

程序因 System.ArgumentException 停止:目标数组不够长...

我能做什么?

【问题讨论】:

  • 不能保证每次从Read 调用中读取 2 个字节。您需要检查您是否实际读取了所需的字节数(Read 的返回值告诉您这一点)。
  • Int16 版本应该可以正常工作。

标签: c# binary int bytearray bitconverter


【解决方案1】:

您可以移动字节中的值以使它们匹配,然后将它们放在一起。如果我正确使用了位,那将是:

int value = (buf[0] << 2) | (buf[1] >> 6);

【讨论】:

    猜你喜欢
    • 2014-03-05
    • 1970-01-01
    • 2013-09-22
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2011-06-24
    相关资源
    最近更新 更多