2016-11-07 65 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. 

}