C 隐式转换为无符号类型的负整数

C 隐式转换为无符号类型的负整数,c,gcc,enums,bit-fields,C,Gcc,Enums,Bit Fields,如何为以下内容设置/取消设置枚举值。使用gcc,我得到了这个恼人的警告: test.c:37: warning: negative integer implicitly converted to unsigned type test.c:39: warning: negative integer implicitly converted to unsigned type test.c:41: warning: negative integer implicitly converted to un

如何为以下内容设置/取消设置枚举值。使用gcc,我得到了这个恼人的警告:

test.c:37: warning: negative integer implicitly converted to unsigned type
test.c:39: warning: negative integer implicitly converted to unsigned type
test.c:41: warning: negative integer implicitly converted to unsigned type
test.c:43: warning: negative integer implicitly converted to unsigned type
代码是:

#include <stdio.h>
#include <string.h>

typedef enum {
 ONE = 0x1,
 TWO = 0x2,
 THREE = 0x4,
 FOUR = 0x8,
} options;

static const char *byte_to_binary (int x)
{
  int z;
  static char b[9];
  b[0] = '\0';

  for (z = 256; z > 0; z >>= 1)
    {
    strcat(b, ((x & z) == z) ? "1" : "0");
    }

  return b;
}

int main(int argc, char *argv[])
{
  options o = 0;
  printf( "%s\n", byte_to_binary(o));
  o |= ONE;
  printf( "%s\n", byte_to_binary(o));
  o |= TWO;
  printf( "%s\n", byte_to_binary(o));
  o |= THREE;
  printf( "%s\n", byte_to_binary(o));
  o |= FOUR;
  printf( "%s\n", byte_to_binary(o));
  o &= ~FOUR;
  printf( "%s\n", byte_to_binary(o));
  o &= ~THREE;
  printf( "%s\n", byte_to_binary(o));
  o &= ~TWO;
  printf( "%s\n", byte_to_binary(o));
  o &= ~ONE;
  printf( "%s\n", byte_to_binary(o));

  return 0;
}
#包括
#包括
类型定义枚举{
1=0x1,
二=0x2,
三=0x4,
四=0x8,
}选择权;
静态常量字符*字节到二进制(整数x)
{
intz;
静态字符b[9];
b[0]='\0';
对于(z=256;z>0;z>>=1)
{
strcat(b,((x&z)==z)?“1”:“0”);
}
返回b;
}
int main(int argc,char*argv[])
{
选项o=0;
printf(“%s\n”,字节_到_二进制(o));
o |=一个;
printf(“%s\n”,字节_到_二进制(o));
o |=两个;
printf(“%s\n”,字节_到_二进制(o));
o |=三个;
printf(“%s\n”,字节_到_二进制(o));
o |=四个;
printf(“%s\n”,字节_到_二进制(o));
o&=~4;
printf(“%s\n”,字节_到_二进制(o));
o&=~3;
printf(“%s\n”,字节_到_二进制(o));
o&=~2;
printf(“%s\n”,字节_到_二进制(o));
o&=~1;
printf(“%s\n”,字节_到_二进制(o));
返回0;
}

由于您的枚举不包含任何负整数常量,我想GCC已经为您的枚举提供了
无符号的
int类型。现在这些表达像

o &= ~FOUR
相当于

o = o & ~FOUR
在RHS上,
o
是无符号整数,
~FOUR
是有符号整数,根据类型转换规则,有符号整数将转换为无符号整数。另外,
~FOUR
是负数,因此您会收到一条警告,提示将负数隐式转换为无符号类型

如果您确信自己的逻辑,就不必担心警告,或者您可以通过使用一个等于负数的伪
enum
将枚举转换为带符号的枚举

差不多

typedef enum {
 DUMMY =-1,
 ONE = 0x1,
 TWO = 0x2,
 THREE = 0x4,
 FOUR = 0x8,
} options;

此外,您的代码具有运行时功能。在函数
byte\u to\u binary
中,您正在检查9位,但您的缓冲区也是9字节。它必须是10个字节,一个用于终止null。使其
静态字符b[10]
和所有内容

由于您的枚举不包含任何负整数常量,我猜GCC为您的枚举提供了
无符号
int类型。现在这些表达像

o &= ~FOUR
相当于

o = o & ~FOUR
在RHS上,
o
是无符号整数,
~FOUR
是有符号整数,根据类型转换规则,有符号整数将转换为无符号整数。另外,
~FOUR
是负数,因此您会收到一条警告,提示将负数隐式转换为无符号类型

如果您确信自己的逻辑,就不必担心警告,或者您可以通过使用一个等于负数的伪
enum
将枚举转换为带符号的枚举

差不多

typedef enum {
 DUMMY =-1,
 ONE = 0x1,
 TWO = 0x2,
 THREE = 0x4,
 FOUR = 0x8,
} options;
此外,您的代码具有运行时功能。在函数
byte\u to\u binary
中,您正在检查9位,但您的缓冲区也是9字节。它必须是10个字节,一个用于终止null。使其
静态字符b[10]和所有内容

这可能会有帮助:这可能会有帮助: