编写一个函数,从数组中提取8位,并将其转换为Decimal



我正试图编写一个函数,该函数从一个6x24的数组中获取8位(只需考虑它一次获取一个字节1位),并将其转换为十进制整数。这意味着总共应该有18个数字。这是我的代码

int bitArray[6][24]; //the Array of bits, can only be a 1 or 0
int ex=0; //ex keeps track of the current exponent to use to calculate the decimal value of a binary digit
int decArray[18]; //array to store decimals
int byteToDecimal(int pos, int row) //takes two variables so you can give it an array column and row
{
  numholder=0; //Temporary number for calculations
  for(int x=pos; x<pos+8;x++) //pos is used to adjust where we start and stop looking at 1's and 0's in a row
  {
    if(bitArray[row][x] != 0)//if the row and column is a 1
    {
      numholder += pow(2, 7-ex);//2^(7-ex), meaning the first bit is worth 2^7, and the last is 2^0      
    }
    ex++;
  }
  ex=0;
  return numholder;
}

然后你可以调用这样的函数

decArray[0]=byteToDecimal(0,0);
decArray[1]=byteToDecimal(8,0);
decArray[2]=byteToDecimal(16,0);
decArray[3]=byteToDecimal(0,1);
decArray[4]=byteToDecimal(8,1);
decArray[5]=byteToDecimal(16,1);

等等。当我在bitArray[0][0]中放入一个1时,调用该函数会得到数字127,而它应该是128。

显然bitArray(或至少涉及的字节)没有用零填充。原因可能各不相同。第二个(疯狂的)原因可能是Arduino C编译器没有用零初始化静态对象(我有过使用Arduino的经验,所以我不能确定)。

在任何情况下,在使用memset(bitArray, 0, sizeof(bitArray))执行其他操作之前,请尝试调用它

这里有一个用纯C编写的演示,演示了通常情况下代码应该可以正常工作。

最新更新