2016-11-07 33 views
-1

我會究竟如何檢查一個bitset矢量給定的「項目」是否是出界位集合矢量INT K掉用C

例如:

struct bitset { 
    unsigned char*vector; 
    int byteSize; 
    int bitSize; 
}; 
// create a new, empty bit vector set of 'size' items 
struct bitset * bitset_new(int size) { 
    struct bitset * theSet; 
    theSet = malloc(sizeof(struct bitset)); 
    theSet->vector = calloc(size, sizeof(char)); 
    theSet->bitSize = size; 
    theSet->byteSize= ((size/8) + 1); 
    return theSet; 
} 
    int bitset_find(struct bitset * this, int k) 
    { 
     int arrayIndex = k/8; 
     int indexPosition = k%8; 
     unsigned int flag = 1; // flag = 0000.....00001 

     flag = flag << indexPosition;  // flag = 0000...010...000 (shifted k positions) 

     if() 
     { 
     } 

    } 

究竟應該我在我的if語句中看看k是否不在我的向量中?

+2

是什麼結構的bitset樣子 – pm100

+0

http://stackoverflow.com/questions/523724/cc-check-if-one-bit-is-set-in -ie-int-variable http://stackoverflow.com/questions/127027/how-to-check-my-byte-flag – pm100

+0

struct bitset { \t unsigned char * vector; \t int byteSize; \t int bitSize; }; – realicado

回答

0

對於通常從位域檢查位,您可以使用按位運算符和&運算符。

您將不得不首先添加一些邏輯來確定您應該查看哪個字節vector

這看起來是這樣的:

int bitset_find(struct bitset * this, int k) 
{ 
    int arrayIndex = k/8; 
    int indexPosition = k%8; 
    unsigned int flag = 1; // flag = 0000.....00001 

    flag = flag << indexPosition;  // flag = 0000...010...000 (shifted k positions) 


    // check to make sure arrayIndex is in range 
    if (arrayIndex > this->byteSize){ 
     return false; // out of range 
    } 

    char vector_byte = this->vector[arrayIndex]; 

    return vector_byte & flag; // return if the field from flag is found in the correct byte from the vector. 

}