Bitset Vector int k超出C的范围

时间:2016-11-07 19:06:43

标签: c vector

我究竟如何检查bitset向量中的给定“item”是否超出范围

例如:

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是否不在我的向量中?

1 个答案:

答案 0 :(得分: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.

}