2012-02-07 66 views
1

我有一个数组作为(用零和1填充) - > ArrayWithContent [5] = {1,0,0,1,1}; 现在我想把它转换成一个变量,这样我就可以读出这个值的总和。如何将元素从数组中移动到变量中C

0001 0011 = 19

for(i=0; i<5; i++) 
{ 
    OneValue = ArrayWithContent[i]; 
    Variable = OneValue; 
    Variable >>= 1;    // Send the zero or one to right.... continue to fill it up 
} 

变量的显示内容现在我想让它显示值19

我知道我没有这个毛病,什么是正确的方法是什么?指针和地址?

回答

5
Variable = 0; 
for (i = 0; i < 5; i++) 
{ 
    Variable = (Variable << 1) | ArrayWithContent[i]; 
} 

这里:

  • (Variable << 1)转移Variable一个位到左侧的当前值。
  • ... | ArrayWithContent[i]ArrayWithContent[i]取代移位值的最低位。
  • 最后,Variable = ...将结果分配回Variable
1

这里是你的循环,固定:

for(i=0; i<5; i++) 
{ 
    OneValue = ArrayWithContent[i]; 
    Variable <<= 1;  // You want to shift to the left to keep the previous value. 
    Variable |= OneValue; // You need to OR the value, else you'd erase the previous value. 
} 
0

如果在大端格式的数据,
......无论是正确的数量和OR一切融合在一起

每个值偏移
value = 0; 
for (i = 0; i < nelems; i++) { 
    value |= (ArrayWithContent[i] << (nelems - i - 1)); 
} 

...或保持1位和OR

value = 0; 
for (i = 0; i < nelems; i++) { 
    value <<= 1; 
    value |= a[i]; 
} 
的下一个比特移位的电流值