有时候,总想验证一些奇怪的想法,干脆就写下来,以备后查。
验证:结构体中bit位使用法
// 测试按位使用
void TestCase_UseBitValue()
{
#pragma pack (push,1)
struct {
char a; // 使用1个字节
char b:1; // 使用字节中的第1个bit位
char c:2; // 使用字节中的第2、3个bit位
char d:4; // 使用字节中的第4、5、6、7个bit位
char e:4; // 使用字节中的第1、2、3、4个bit位
} s; // b、c、d使用同1个字节,e使用1个字节
printf_s("sizeof(s) is %d \n", sizeof(s));
memset(&s, 0, sizeof(s));
byte *p = (byte*)&s;
s.a = 1;
if (s.a > 0)
printf_s("a(%d) is bigger than 0. [0x%x]\n", s.a, *(p));
else
printf_s("a(%d) is not bigger than 0. [0x%x]\n", s.a, *(p));
s.b = 1;
if (s.b > 0)
printf_s("b(%d) is bigger than 0. [0x%x]\n", s.b, *(p+1));
else
printf_s("b(%d) is not bigger than 0. [0x%x]\n", s.b, *(p+1));
s.c = 2;
if (s.c > 0)
printf_s("c(%d) is bigger than 0. [0x%x]\n", s.c, *(p+1));
else
printf_s("c(%d) is not bigger than 0. [0x%x]\n", s.c, *(p+1));
s.d = 8;
if (s.d > 0)
printf_s("d(%d) is bigger than 0. [0x%x]\n", s.d, *(p+1));
else
printf_s("d(%d) is not bigger than 0. [0x%x]\n", s.d, *(p+1));
s.e = 3;
if (s.e > 0)
printf_s("e(%d) is bigger than 0. [0x%x]\n", s.e, *(p+2));
else
printf_s("e(%d) is not bigger than 0. [0x%x]\n", s.e, *(p+2));
#pragma pack(pop)
}
测试结果:
Visual Leak Detector Version 2.5.1 installed.
sizeof(s) is 3
a(1) is bigger than 0. [0x1]
b(-1) is not bigger than 0. [0x1]
c(-2) is not bigger than 0. [0x5]
d(-8) is not bigger than 0. [0x45]
e(3) is bigger than 0. [0x3]
No memory leaks detected.
注意:s.b的值等于-1,原因是s.b为有符号的,且有效位只有1位,若赋值为1,变成有符号数就是-1.
内存结果:黑色为无效bit位。
00000000 00000000 00000000
s.a = 00000000
s.b = 0
s.c = 00
s.d = 0000
s.e = 0000