C中的位域;字节和位
Bit field in C; bytes and bits
我找到了以下示例:
#include <stdio.h>
// Space optimized representation of the date
struct date {
// d has value between 1 and 31, so 5 bits
// are sufficient
unsigned int d : 5;
// m has value between 1 and 12, so 4 bits
// are sufficient
unsigned int m : 4;
unsigned int y;
};
int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
结果是
Size of date is 8 bytes
Date is 31/12/2014
第一个结果我看不懂。 为什么是8个字节?
我的想法:
y
是 4 字节,d
是 5 位,m
是 4 位。总共是 4 字节和 9 位。 1个字节是8位,那么总共是41位。
有很好的解释here
C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case then some compilers may allow memory overlap for the fields whilst other would store the next field in the next word (see comments on bit fiels portability below).
我找到了以下示例:
#include <stdio.h>
// Space optimized representation of the date
struct date {
// d has value between 1 and 31, so 5 bits
// are sufficient
unsigned int d : 5;
// m has value between 1 and 12, so 4 bits
// are sufficient
unsigned int m : 4;
unsigned int y;
};
int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
结果是
Size of date is 8 bytes
Date is 31/12/2014
第一个结果我看不懂。 为什么是8个字节?
我的想法:
y
是 4 字节,d
是 5 位,m
是 4 位。总共是 4 字节和 9 位。 1个字节是8位,那么总共是41位。
有很好的解释here
C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case then some compilers may allow memory overlap for the fields whilst other would store the next field in the next word (see comments on bit fiels portability below).