簡體   English   中英

提取特定范圍的位並在C中找到它們之間的零個數

[英]Extracting a particular range of bits and find number of zeros between them in C

我想在整數變量中提取特定范圍的位。

例如:0xA5(10100101)

我想從bit2提取到bit5。 即1001到一個變量,並在它們之間計數零。

我有另一個給出起點的變量,這意味着在這種情況下,變量的值為2。因此可以通過0xA5 >> 2來找到起點。第5位是此處的隨機位置。 6或7。主要思想是在第二個位之后將哪個位設置為1。 我必須解壓..

我該如何做剩下的部分?

假設您正在處理變量的unsigned int 您將必須構造適當的蒙版。

假設您想要從位置x到位置y的位,則掩碼中必須有y - x + 1 1s

您可以通過-

int digits = y - x + 1;
unsigned int mask = 1u << digits - 1;

現在,您需要從初始數字中刪除較低的x位,方法是-

unsigned int result = number >> x;

最后應用遮罩刪除高位-

result = result & mask;

您可以使用遮罩和“&”(與)操作:

a = 0xA5;
a = a >> OFFSET; //OFFSET 
mask = 0x0F; // equals 00001111
a = a & mask; 

在您的示例中a = 0xA5(10100101),偏移量為2。

  • a >> 2 a現在等於0x29(00101001)
  • a&0x0F(00101001 AND 00001111)= 00001001 = 0x09

在此示例中,我們將0或1個值放入數組。 之后,您可以根據需要處理數組。

#include <stdio.h>
#include <stdint.h>

int main(int argc, char **argv) {
    uint8_t value = 0xA5;
    unsigned char bytes[8];
    unsigned char i;

    for (i = 0; i < 8; i++) {
        bytes[i] = (value & (1 << i)) != 0 ? 1 : 0;
    }

    for (i = 0; i < 8; i++) {
        printf("%d", bytes[i]);
    }

    return 0;
}

如果要從偏移量X位,則向右移X

如果需要Y位,則掩碼(移位后)將為2 Y的冪減一(例如,對於具有四個位的2,乘以4的冪為16,則減一為15,即1111二進制) 。 這可以通過使用Y位左移並減去1

但是,如果要計算所需位中的零個數(僅右移),則不需要屏蔽。 循環Y次,每次向左移動1 ,然后按位檢查值是否為零。 如果是,則增加一個計數器。 在循環結束時,計數器為零。


將其全部放入代碼中:

// Count the number of zeros in a specific amount of bits starting at a specific offset
// value is the original value
// offset is the offset in bits
// bits is the number of bits to check
unsigned int count_zeros(unsigned int value, unsigned int offset, unsigned int bits)
{
    // Get the bits we're interested in the rightmost position
    value >>= offset;

    unsigned int counter = 0;  // Zero-counter
    for (unsigned int i = 0; i < bits; ++i)
    {
        if ((value & (1 << i)) == 0)
        {
            ++counter;  // Bit is a zero
        }
    }

    return counter;
}

要與示例數據一起使用,您需要:

count_zeros(0xa5, 2, 4);

結果應為2 如果您看到此實時節目,該怎么辦

int32_t do_test(int32_t value, int32_t offset)
{
    int32_t _zeros = 1;
    value >>= offset;    

    int i = 1;

    while(1) {
        if((value >> i) % 2 == 0) {
            _zeros += 1;
            i++;
        } else {
            break;
        }
    }
}
int result = (0xA5 >> 2) & 0x0F;

&運算符的真值表

 |    INPUTS  | OUTPUT |
 -----------------------
 |  0   |  0  |    0   |
 |  0   |  1  |    0   |
 |  1   |  0  |    0   |  
 |  1   |  1  |    1   |
 -----------------------  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM