【问题标题】:Bitset Vector int k out of bounds in C位集向量 int k 在 C 中超出范围
【发布时间】:2017-03-21 05:45:06
【问题描述】:

我将如何检查位集向量中的给定“项目”是否超出范围

例如:

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

【问题讨论】:

标签: c vector


【解决方案1】:

一般来说,要检查位域中的位,您将使用按位和&amp; 运算符。

您必须先添加一些逻辑来确定您应该查看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.

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    相关资源
    最近更新 更多