写出下列程序在X86上的运行结果
struct mybitfields { unsigned short a : 4; unsigned short b : 5; unsigned short c : 7; } test void main(void) { int i; test.a = 2; test.b = 3; test.c = 0; i = *((short *)&test); printf("%d\n", i); }
0100 | 11000 | 0000000 |
a | b | c |
class my { int a; int b; int c; }; int main() { my test; int x; int y; }
《MISRA》—— Only used when storage space is at a premium.
“Almost everything about fields is implementation-dependent”
《The C Programming Language》
programs using bit-field are not portable.
如果相邻位域字段的类型相同,且其位宽之和小于sizeof(类型)则后面的字段将紧邻前一个字段存储,直到不能容纳为止;
如果相邻位域字段的类型相同,但其位宽之和大于sizeof(类型),则后面的字段将从新的存储单元开始,其偏移量为其类型大小的整数倍;
3. 如果相邻的位域字段的类型不同,则各编译器的具体实现有差异,VC6采取不压缩方式,Dev-C++和GCC都采取压缩方式;
The order of allocation of bit-fields within a unit is implementation-defined
(即:大端/小端)
by (C99 标准 6.2.7.1)
珍爱生命,慎用位域!
除非你真的知道你在干嘛。
低地址字节 | | |
高地址字节 | | |
低地址字节 | b3b2b1b0 | a3a2a1a0 |
高地址字节 | c6c5c4c3 | c2c1c0b4 |
低地址字节(LSB) | 0011 | 0010 |
高地址字节(MSB) | 0000 | 0000 |
输出#include <stdio.h>#include <stdlib.h>struct mybitfields {unsigned short a : 4;unsigned short b : 5;unsigned short c : 7;};int k, i; /* 为了避免i,k干扰,我将k,i放到全局变量里.占用堆空间。*/int main(void) {struct mybitfields high, test, low;/* high,test,low在栈中占用的空间由高到低。但是它们内部的空间占用仍然符合结构体的位域的规则。*/test.a = 2;test.b = 3;test.c = 0;high.a = 4;high.b = 5;high.c = 0;low.a = 1;low.b = 2;low.c = 0;i = *((short *)&test);printf("short test: %08X\n", i);k = *((int *)&test);printf("int test: %08X\n", k);k = *((int *)&high);printf("int high: %08X\n", k);k = *((int *)&low);printf("int low: %08X\n", k);}
short test: 00000032 int test: 00540032 int high: CCD00054 int low: 00320021 |