C 使用8位整数作为标志掩码

C 使用8位整数作为标志掩码,c,bit-manipulation,C,Bit Manipulation,对于自定义数据结构,我有65个不同的标志(选项)。现在看起来是这样的: struct CustomDataStruct { int Something; unsigned char Flags[9] }; 这样我可以存储多达72个标志(剩下7个,以防万一我决定添加更多)。我想为每个标志使用一个单独的位,因此我提出了以下建议: void SetFlag(struct CustomDataStructure* Struct, int FlagNr) { // Error c

对于自定义数据结构,我有65个不同的标志(选项)。现在看起来是这样的:

struct CustomDataStruct {
    int Something;
    unsigned char Flags[9]
};
这样我可以存储多达72个标志(剩下7个,以防万一我决定添加更多)。我想为每个标志使用一个单独的位,因此我提出了以下建议:

void SetFlag(struct CustomDataStructure* Struct, int FlagNr) {
    // Error checking and other stuff here
    int index = FlagNr / 8; array.
    Struct->Flags[index] |= 1 << (__________);

}
void SetFlag(struct CustomDataStructure*struct,int FlagNr){
//这里有错误检查和其他东西
int index=FlagNr/8;数组。

Struct->Flags[index]|=1位通常从最低有效位(最右边)开始索引,因为在大多数上下文中这更有意义。如果要反转,只需执行
1>(FlagNr%8)
void setFlag(Struct CustomDataStructure*foo,int-flagnindex){
断言(flagIndex>=0&&flagIndex<72);//防御编程!
size_t arrayIndex=flagIndex/8;
int-bitShift=flagIndex%8;
//如果需要反向(小端)位顺序,则从7中减去:
位移位=7-位移位;
//此代码已扩展以提高可读性。优化编译器仍将生成快速代码:
uint8_t flags=foo->flags[arrayIndex];
flags=flags |(1 flags[arrayIndex]=flags;
}

数组查找工作起来很容易,而不是进行位移位。
FlagNr
包含基于零的位索引,因此值0是第一个数组元素中的第一位

void setFlag( struct CustomDataStructure* thing, int FlagNr) {
    static uint8_t  masks[] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};
    size_t   index = FlagNr % 8;
    size_t   xndex = FlagNr / 8;
    thing->Flags[xndex] |= masks[index];
}

挑剔:我建议不要在实际代码中使用
Struct
作为标识符。还要避免使用术语
Number
(“
Nr
”)和
Index
来指代与“Number”表示基数1而“Index”相同的内容暗示基数为0。如果您正在编写可移植C,那么我也建议使用显式的
uint8_t
而不是
char
,因为C支持非八位字节平台:@Dai感谢您提供这些提示。这只是伪代码,在我的实际项目中,标志掩码被定义为
uint8_t标志[9]
,标识符不是我示例中列出的通用标识符,而是更具描述性的标识符。我认为OP希望位索引反转。@AlexanderZhang感谢我没有得到该部分。因此位掩码数组需要反转顺序。工作起来很有魅力。因此,要获得标志状态,将
bool getFlag(struct CustomDataStructure*struct,int FlagNr){return struct->flagns[FlagNr/8]|1@Svtyros使用
&
检查位是否已设置,而不是
。否则,您是正确的。
void setFlag( struct CustomDataStructure* thing, int FlagNr) {
    static uint8_t  masks[] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};
    size_t   index = FlagNr % 8;
    size_t   xndex = FlagNr / 8;
    thing->Flags[xndex] |= masks[index];
}