【问题标题】:How to convert bytes to an int using bit converter in c#如何在 C# 中使用位转换器将字节转换为 int
【发布时间】:2020-03-11 09:00:18
【问题描述】:

我有一个代码可以返回一个字节或更多或更少的字节数组。问题在于,有时在转换字节时会出现错误,因为我无法确定何时需要使用 toInt32、toInt64 或 toInt16。另一个问题是,有时当我得到一个字节时,我无法使用上述方法转换这个字节,因为我不断收到错误。那么如何根据字节的长度或大小来确定我应该使用哪种方法。

//as in array of bytes byte[]
  var response = this.cc.Sendcc("SERIAL_NUMBER", 0x05, 0x80, 0x64, 0x04, 0x01, 0x21, (byte)1, (byte)1);

if (response .Length == 1)
{
     toInt32SerialNumber = BitConverter.ToInt16(response , 0);
}
else
{
     toInt32SerialNumber = BitConverter.ToInt32(response , 1);
}

【问题讨论】:

  • 可能是一个没有实际意义的问题,但为什么不简单地选择尽可能大的 int,即 int64 呢?
  • “我不断收到错误” - 什么错误?
  • 目标数组的长度不足以复制集合中的所有项目。检查一个
  • 为什么将BitConverter.ToInt32(response , 1); 的起始索引指定为1?不应该是0吗?
  • 如果您向我们展示各种长度的 response 内容以及转换这些字节时所期望的结果,将会很有帮助。

标签: c# bitconverter


【解决方案1】:

@moe1792

请试试这段代码,在 c# 中使用位转换器将字节数组转换为 int:

byte[] bytes = { 0, 0, 0, 25 };

if (BitConverter.IsLittleEndian)
    Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int : {0}", i);

希望以上代码对你有用。

谢谢。

【讨论】:

  • 没有必要尝试@通知OP。 1) 他们会自动收到答案通知,以及 2) @ 通知在答案中无论如何都不起作用。
【解决方案2】:

尝试以下,它将处理“响应”的所有可能值/字节:

if(response.Length<8)
{
    byte[] temp = new byte[8];
    response.CopyTo(temp, 0);
    response = temp;
}

UInt64 toInt32SerialNumber = BitConverter.ToUInt64(response, 0);

此外,StartIndex 应该为零,除非您需要有意跳过某些数据!

【讨论】:

  • 它没有。如果response 中的字节数少于 8 个,则会给出错误“System.ArgumentException: '目标数组不够长,无法复制集合中的所有项目。请检查数组索引和长度。'”
  • 是的,你是对的。我认为稍微调整一下就可以解决,我已经修改了我的答案,请重新检查。
猜你喜欢
  • 1970-01-01
  • 2011-02-10
  • 2012-08-27
  • 2011-02-12
  • 1970-01-01
  • 2016-03-04
  • 2016-02-20
相关资源
最近更新 更多