![](/img/trans.png)
[英]How to move last element of array to the first element of another array in c programming
[英]How to move element from an array into an variable in C
我有一個數組(用零和一填充)-> 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
}
顯示變量的內容我現在希望它顯示值19。
我知道我做錯了,正確的方法是什么? 指針和地址?
Variable = 0;
for (i = 0; i < 5; i++)
{
Variable = (Variable << 1) | ArrayWithContent[i];
}
這里:
(Variable << 1)
移動的電流值Variable
的一個比特到左邊。 ... | ArrayWithContent[i]
... | ArrayWithContent[i]
替換為偏移值的最低位顯著ArrayWithContent[i]
Variable = ...
將結果分配回Variable
。 這是您的循環,已修復:
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.
}
如果您使用大端格式的數據,
...要么將每個值都偏移正確的數量,要么將所有值或在一起
value = 0;
for (i = 0; i < nelems; i++) {
value |= (ArrayWithContent[i] << (nelems - i - 1));
}
...或繼續將當前值移位1位,或繼續將下一位移位
value = 0;
for (i = 0; i < nelems; i++) {
value <<= 1;
value |= a[i];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.