我正在尝试编写一个从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);
等。当我将一个1放入bitArray [0] [0]时,调用该函数给出数字127,当它应该是128时。
答案 0 :(得分:0)
显然bitArray
(或至少涉及的字节)没有填充零。原因可能有所不同。很可能你从之前的操作中得到了一些剩余的东西。第二个(疯狂)原因是Arduino C编译器可能没有用零初始化静态对象(我对Arduino有过经验,所以我无法确定)。
在任何情况下,尝试在使用它执行其他操作之前调用memset(bitArray, 0, sizeof(bitArray))
。
这是一个demo written in plain C,证明通常你的代码应该可以正常工作。