如何在不检查每个元素的情况下立即检查结构的零值

How to instantly check the zero value of a structure without checking its each element?

本文关键字:检查 结构 情况下 不检查 元素      更新时间:2023-10-16

假设我有一个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的地址按声明的顺序增加。指向结构对象,经过适当转换,指向其初始成员(或者如果该成员是位字段,然后到它所在的单元),反之亦然。可能有未命名的结构对象中的填充,但不在其开头