Chr*_*ian 1 c arrays for-loop bit-manipulation
我有一个数组(用零和一个填充) - > ArrayWithContent [5] = {1,0,0,1,1}; 现在我希望将其转换为变量,以便我可以读出它的总值.
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
}
Run Code Online (Sandbox Code Playgroud)
显示变量的内容我现在希望它显示值19.
我知道我做错了,正确的方法是什么?指针和地址?
Variable = 0;
for (i = 0; i < 5; i++)
{
Variable = (Variable << 1) | ArrayWithContent[i];
}
Run Code Online (Sandbox Code Playgroud)
这里:
(Variable << 1)将Variable一位的当前值向左移动.... | ArrayWithContent[i]用...替换移位值的最低有效位ArrayWithContent[i].Variable = ...将结果分配回来Variable.