[英]Effective bits calculation along the array in specified position on STM32
您可以循環數組值並使用按位和運算符測試位,如下所示:
int arr[] = {1,2,3,4,5};
// 1 - 001
// 2 - 010
// 3 - 011
// 4 - 100
// 5 - 101
int i, bitcount = 0;
for (i = 0; i < 5; ++i){
if (arr[i] & (1 << 2)){ //testing and counting the 3rd bit
bitcount++;
}
}
printf("%d", bitcount); //2
請注意,我選擇1 << 2
來測試右邊的第三位或最低的第三位,以便於顯示。 現在, bitCount
現在將保存2
,這是設置為1
的3rd
位的數目。
在您的情況下,您需要檢查第5位,該位可以表示為:
1 << 4
0x10000
16
和第8位:
1 << 7
0x10000000
256
因此,將其調整為適合您的位數將為您提供:
int i, bitcount8 = 0, bitcount5 = 0;
for (i = 0; i < your_array_size_here; ++i){
if (arr[i] & 0x10000000){
bitcount8++;
}
if (arr[i] & 0x10000){
bitcount5++;
}
}
如果您需要計數很多,那么該解決方案就不好了,最好創建一個數組,然后用另一個for
循環來計算它們:
int i, j, bitcounts[8] = {0};
for (i = 0; i < your_array_size_here; ++i){
for (j = 0; j < 8; ++j){
//j will be catching each bit with the increasing shift lefts
if (arr[i] & (1 << j)){
bitcounts[j]++;
}
}
}
在這種情況下,您將按其索引訪問位數:
printf("%d", bitcounts[2]); //2
假設OP要計算有效位
size_t countbits(uint8_t *array, int pos, size_t size)
{
uint8_t mask = 1 << pos;
uint32_t result = 0;
while(size--)
{
result += *array++ & mask;
}
return result >> pos;
}
讓位位置差(在這種情況下為diff
)為diff
。
如果2 diff > n,則代碼可以同時將兩個位相加。
void count(const uint8_t *Array, size_t n, int *bit7sum, int *bit4sum) {
unsigned sum = 0;
unsigned mask = 0x90;
while (n > 0) {
n--;
sum += Array[n] & mask;
}
*bit7sum = sum >> 7;
*bit4sum = (sum >> 4) & 0x07;
}
如果處理器具有快速乘法並且n
仍然不太大,例如n < pow(2,14)
在這種情況下。 (或者一般情況下n < pow(2,8)
)
void count2(const uint8_t *Array, size_t n, int *bit7sum, int *bit4sum) {
// assume 32 bit or wider unsigned
unsigned sum = 0;
unsigned mask1 = 0x90;
unsigned m = 1 + (1u << 11); // to move bit 7 to the bit 18 place
unsigned mask2 = (1u << 18) | (1u << 4);
while (n > 0) {
n--;
sum += ((Array[n] & mask1)*m) & mask2;
}
*bit7sum = sum >> 18;
*bit4sum = ((1u << 18) - 1) & sum) >> 4);
}
算法:代碼使用掩碼,乘法,掩碼將2位分開。 當高位移位到高位時,低位保持在低位。 然后發生並行添加。
循環避免了循環本身之外的任何分支。 這可以使代碼更快速。 YMMV 。
如果n
更大,則將其分解為對count2()
多次調用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.