将16字节数组响应转换为十进制数

时间:2014-02-14 13:59:37

标签: c# arrays

我正在处理一个应用程序,其中我收到了一个16字节的数组响应。在该响应中,将设置1位以指示位置值。例如,我可能会得到:

0000 01000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000

表示设备#5 已响应(第一位代表设备#0)。

是否有一种简单的方法可以将此长度的字节数组转换为十进制值?

3 个答案:

答案 0 :(得分:1)

Decimal类不是表示此类数据的适当方式。您可能正在寻找的是BitArray class

答案 1 :(得分:0)

如果我正确理解您的问题,您可以使用for-loop,计数器将是您的设备号。

修改:添加了代码示例

int n = 0;

// Loop trough the byte array.
for(n = 0; n < bytearray.Length; n++)
{
   // Exit the loop as soon as the indexed byte from the array is 1.
   if(bytearray[n] != null && bytearray[n] == 1)
   {
      break;
   }
}

// Here you can string your device name together.
string deviceName = "device #" + n;

备注:其实我不明白你的例子。为什么说16个字节,但每个组都是4位。你是怎么从那个bytearray得到设备号5的?

答案 2 :(得分:0)

尝试这样的事情:

byte[] yourByteArr = { 0, 0, 32, 0, };

var firstSetBit = (new BitArray(yourByteArr)).Cast<bool>()
    .Select(Tuple.Create<bool, int>).FirstOrDefault(x => x.Item1);
int indexOfFirstSetBit = firstSetBit != null ? firstSetBit.Item2 : -1;

如果不能设置任何位,只需执行:

int indexOfFirstSetBit = (new BitArray(yourByteArr)).Cast<bool>()
    .Select(Tuple.Create<bool, int>).First(x => x.Item1).Item2;