如何在不检查每个元素的情况下立即检查结构的零值
How to instantly check the zero value of a structure without checking its each element?
假设我有一个byte
结构,如下所示:
struct one_byte
{
char b1 : 1,
b2 : 1,
b3 : 1,
b4 : 1,
b5 : 1,
b6 : 1,
b7 : 1,
b8 : 1;
}foo;
在某些情况下,我需要检查(foo == 0)
,然后我必须执行八个命令:
if(foo.b1 == 0 &&
foo.b2 == 0 &&
foo.b3 == 0 &&
...and so on
有便携式&只需一个命令就可以立即检查零值的方便方法?我试过函数&模板,它们的执行速度非常慢。我尝试了并集,我的编译器不支持位[数组]。。。。
使用联合,这就是的用途
union {
struct {
char b1:1,b2:1,b3:1,b4:1,b5:1,b6:1,b7:1,b8:1;
} bits;
unsigned char byte;
} u;
然后您可以直接分配字节
u.byte = 15;
或位单独
u.bits.b3 = 1;
示例
int main() {
u.byte = 0;
printf("%xn", u.byte);
u.bits.b3 = 1;
u.bits.b4 = 1;
printf("%xn", u.byte);
return 0;
}
将输出
0
c // 12 in decimal, since b3 and b4 are set to 1
struct one_byte zero = { 0 };
!memcmp (&variable_1, &zero, sizeof (struct one_byte))
这可能是一个解决方案,但我不知道这是否是一个聪明的主意。也许只是取消或多或少标准的比特设置方式会做得更好:
#define SET_BIT(v, n) (v) |= (1<<n)
#define CLR_BIT(v, n) (v) &= ~(1<<n)
#define GET_BIT(v, n) ((v) & ~(1<<n) == 0)
char foo;
if (foo == 0)
so_what ();
#include <iostream>
#include <cstring>
using namespace std;
struct one_byte{
char b1:1;
char b2:1;
char b3:1;
char b4:1;
char b5:1;
char b6:1;
char b7:1;
char b8:1;
}__attribute__((packed));
int main(int argc, char *argv[])
{
one_byte b1;
int j;
memcpy(&j, &b1, sizeof(b1));
if(j == 0) cout << "Its 0";
else cout << "It's not 0";
return 0;
}
上面的节目怎么样?
!*((unsigned char *) &foo)
应该做这个把戏。请注意,我使用了!
运算符来检查零值——如果您不喜欢,可以使用== 0
。
听起来你想堕落,那么:怎么样
struct one_byte Other; // a real variable
...
if(*(char*)&Other == ' ')
我认为这不会显著提高性能。
if (memcmp(&foo, " ", 1) == 0)
{
// all zero
}
我手头没有C++规范,但C99规范6.7.2.11/13说(重点是我的):
在结构对象中,非位字段成员和位字段所在的单位resident的地址按声明的顺序增加。指向结构对象,经过适当转换,指向其初始成员(或者如果该成员是位字段,然后到它所在的单元),反之亦然。可能有未命名的结构对象中的填充,但不在其开头。
相关文章:
- C++概念:如何使用'concept'检查模板化结构的属性?
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 检查结构中的模板类型
- C++ - 检查结构数据类型中的单词是否为回文
- 如何检查助推融合序列是否为自适应结构
- 助推.测试检查结构是否相等
- C++检查结构为空
- 检查结构中的更改
- 检查 c++ 结构是否在集合中
- C++检查结构中的所有状态位
- 检查结构数组是否为空
- 检查结构是否不在矢量中
- 有没有办法检查结构中是否存在成员
- 如何在编译时检查结构的大小
- 如何检查结构的类型或字段是否存在
- 如何检查结构在 C 或 C++ 中是否为 NULL
- 检查结构体是否为NULL或未设置,即使它的有操作符相等
- 使用模板检查结构体中的字段,启用函数if,并在失败时给出一个漂亮的错误消息
- 在C++中检查结构是否对齐或包含间隙
- 如何在不检查每个元素的情况下立即检查结构的零值