正确的方法是使用二进制位域打印数字
the right way use bit field print number in binary
这是我使用二进制位字段打印 int 数字找到的代码,但我也仅使用 unsigned
、int
读取该位字段的类型,因此,它是否合法此代码使用 char
类型?
struct bits
{
unsigned char ch1 : 1;//01
unsigned char ch2 : 1;
unsigned char ch3 : 1;
unsigned char ch4 : 1;
unsigned char ch5 : 1;
unsigned char ch6 : 1;
unsigned char ch7 : 1;
unsigned char ch8 : 1;
};
void main()
{
int data = -1;
int length = 4;
struct bits *p = &data;
while (length--)
{
printf("%d%d%d%d %d%d%d%d ",
(p + length)->ch8,
(p + length)->ch7,
(p + length)->ch6,
(p + length)->ch5,
(p + length)->ch4,
(p + length)->ch3,
(p + length)->ch2,
(p + length)->ch1
);
}
system("pause");
}
GCC 是allowing作为位域的任何整数类型,与 C99 和 C11 标准相反:
Allowable bit-field types other than _Bool, signed int, and unsigned
int (C99 and C11 6.7.2.1).
Other integer types, such as long int, and
enumerated types are permitted even in strictly conforming mode.
A bit-field shall have a type that is a qualified or unqualified version of _Bool
, signed int
, unsigned int
, or some other implementation-defined type.
某些编译器允许使用 unsigned char
作为 "implementation-defined type"。
(p + length)->ch8
将通过通常的 整数提升 作为可变参数函数的参数。因此 ch8
将被提升为匹配 "%d"
.
的 int
代码可以使用 unsigned
struct bits {
unsigned ch1 : 1;//01
unsigned ch2 : 1;
unsigned ch3 : 1;
unsigned ch4 : 1;
unsigned ch5 : 1;
unsigned ch6 : 1;
unsigned ch7 : 1;
unsigned ch8 : 1;
};
这是我使用二进制位字段打印 int 数字找到的代码,但我也仅使用 unsigned
、int
读取该位字段的类型,因此,它是否合法此代码使用 char
类型?
struct bits
{
unsigned char ch1 : 1;//01
unsigned char ch2 : 1;
unsigned char ch3 : 1;
unsigned char ch4 : 1;
unsigned char ch5 : 1;
unsigned char ch6 : 1;
unsigned char ch7 : 1;
unsigned char ch8 : 1;
};
void main()
{
int data = -1;
int length = 4;
struct bits *p = &data;
while (length--)
{
printf("%d%d%d%d %d%d%d%d ",
(p + length)->ch8,
(p + length)->ch7,
(p + length)->ch6,
(p + length)->ch5,
(p + length)->ch4,
(p + length)->ch3,
(p + length)->ch2,
(p + length)->ch1
);
}
system("pause");
}
GCC 是allowing作为位域的任何整数类型,与 C99 和 C11 标准相反:
Allowable bit-field types other than _Bool, signed int, and unsigned int (C99 and C11 6.7.2.1).
Other integer types, such as long int, and enumerated types are permitted even in strictly conforming mode.
A bit-field shall have a type that is a qualified or unqualified version of
_Bool
,signed int
,unsigned int
, or some other implementation-defined type.
某些编译器允许使用 unsigned char
作为 "implementation-defined type"。
(p + length)->ch8
将通过通常的 整数提升 作为可变参数函数的参数。因此 ch8
将被提升为匹配 "%d"
.
int
代码可以使用 unsigned
struct bits {
unsigned ch1 : 1;//01
unsigned ch2 : 1;
unsigned ch3 : 1;
unsigned ch4 : 1;
unsigned ch5 : 1;
unsigned ch6 : 1;
unsigned ch7 : 1;
unsigned ch8 : 1;
};