C位域

本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/ztz0223/archive/2008/12/24/3599016.aspx


很早想说说这个问题了,经常也会有很多公司拿位域出来考人,呵呵要真的想弄清楚还要一点点的分析。

这里先看看网宿的一道笔试题目,这道题目我之前是复制网上的,结果不对,修改了一下,可以正确运行了,谢谢(imafish_i )提醒:

//假设硬件平台是intel x86(little endian)

typedef unsigned int uint32_t;
void inet_ntoa(uint32_t in)
{
char b[18];
register char *p;
p = (char *)∈
#define UC(b) (((int)b)&0xff)
sprintf(b, "%d.%d.%d.%d\n", UC(p[0]), UC(p[1]), UC(p[2]), UC(p[3]));
printf(b);
}
int main()
{
inet_ntoa(0x12345678);
inet_ntoa(0x87654321);
}

有点难度的一道题目,其实理解的也很简单。



位域(Bit-fields)分析



位域是c++和c里面都有的一个概念,但是位域有一点要注意的有很多问题我们一样样的看:



大端和小端字节序


这个很简单,就是起始点该怎么确定。
先看一个程序:


union {
struct
{
unsigned char a1:2;
unsigned char a2:3;
unsigned char a3:3;
}x;
unsigned char b;
}d;

int main(int argc, char* argv[])
{
d.b = 100;
return 0;
}
那么x的a1,a2,a3该怎么分配值,100的二进制是:0110 0100,那么a1到a3是不是就是依次取值恩?
不是!
我们先看看100分配位的低端是左边的0还是右边的0?很明显是右边的0,那么我们再看a1到a3的分配是从低端到高端的
那么,对应的应该是
<<<<<<--内存增大
a3 a2 a1
011 001 00


内存增大之所以这么写是因为,011是在高位!
而不是通常认为的的:
a1 a2 a3
011 001 00

还有一个情况多见就是一个二进制的数字转化为点分十进制数值,如何进行,这里涉及到大端还是小端的问题,上面没有涉及,主要

是因为上面是一个字节,没有这个问题,多个字节就有大端和小端的问题了,如下:

int main(int argc, char* argv[])
{
int a = 0x12345678;
char *p = (char *)&a;
char str[20];
sprintf(str,"%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
printf(str);
return 0;
}
这个程序假设是小端字节序,那么结果是什么?
我们看看应该怎么放置呢?
每个字节8位,0x12345678分成4个字节,就是从高位字节到低位字节:12,34,56,78,那么这里该怎么放?如下:
---->>>>>>内存增大
78 56 34 12



因为这个是小端,那么小内存对应低位字节,就是上面的结构。

接下来的问题又有点迷糊了,就是p怎么指向,是不是指向0x12345678的开头--12处?不是!12是我们所谓的开头,但是不是内存

的开始处,我们看看内存的分布,我们如果了解p[0]到p[1]的操作是&p[0]+1,就知道了,p[1]地址比p[0]地址大,也就是说p的地址

也是随内存递增的!

12 ^ p[3]
|
34 | p[2]
|
56 | p[1]
|
78 | p[0]
内存随着箭头增大!同时小端存储也是低位到高位在内存中的增加!
这样我们知道了内存怎么分布了

那么:

sprintf(str,"%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
str就是这个结果了:
120.86.52.18

那么反过来呢?

int main(int argc, char* argv[])
{
int a = 0x87654321;
char *p = (char *)&a;
char str[20];
sprintf(str,"%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
printf(str);
return 0;
}
依旧是小端,8位是一个字节那么就是这样的啦:

87 ^ p[3]
|
65 | p[2]
|
43 | p[1]
|
21 | p[0]

结果是:
33.67.101.-121
为什么是负的?因为系统默认的char是有符号的,本来是0x87也就是135,大于127因此就减去256得到-121
那么要正的该怎么的弄?
如下就是了:

int main(int argc, char* argv[])
{
int a = 0x87654321;
unsigned char *p = (unsigned char *)&a;
char str[20];
sprintf(str,"%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
printf(str);
return 0;
}
用无符号的!
结果:
33.67.101.135



位域的符号(正负)



看完大端和小端以后,再看看位域的取值的问题,上面我们谈到了一些,首先就是位域是按照位来取值的跟我们的int是32位char是8

位一样,很简单,但是,要注意一点就是位域也有正负,指有符号属性的,就是最高位表示的,也会涉及到补码这个一般被认为非常

恶心的东西,看看程序吧:


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

int main(int argc, char** argv)
{
union
{
struct
{
unsigned char a:1;
unsigned char b:2;
unsigned char c:3;
}d;
unsigned char e;
} f;
f.e = 1;
printf("%d\n",f.d.a);
return 0;
}

<小端>
那么输出是什么?
换一下:

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

int main(int argc, char** argv)
{
union
{
struct
{
char a:1;
char b:2;
char c:3;
}d;
char e;
} f;
f.e = 1;
printf("%d\n",f.d.a);
return 0;
}

输出又是什么?

小端的话,那么,再d.a上面分得1,而这个是无符号的char,那么前者输出是1,没有问题,第二个输出是-1,哈哈。
为什么?
第二个是无符号的,就一个位分得1,那么就是最高位分得1,就是负数,负数用的补码,实际的值是取反加1,就是0+1=1,再取符

号负数,就是-1.



整型提升



最后的打印是用的%d,那么就是对应的int的打印,这里的位域肯定要提升,这里有一点,不管是提升到有符号还是无符号,都是自

己的符号位来补充,而不改变值的大小(这里说的不改变值大小是用相同的符号属性来读取),负数前面都补充1,正数都是用0来补充

,而且也只有这样才能保证值不变,比如,char提升到int就是前面补充24个char的最高位,比如:

char c = 0xf0;
int p = c;
printf("%d %d\n",c,p);
输出:-16 -16
p实际上就是0xfffffff0,是负数因此就是取反加1得到
c是一个负数那么转化到x的时候就是最高位都用1来代替,得到的数不会改变值大小的。
再看:

char c = 0xf0;
unsigned int x = c;
printf("%u\n",x);
得到的结果是4294967280,也就是0xfffffff0,记住,无符号用%u来打印。



地址不可取


最后说的一点就是位域是一个字节单元里面的一段,是没有地址的!



附录



最后附上《The C Book》这本书的一段说法:
While we're on the subject of structures, we might as well look at bitfields. They can only be declared inside a

structure or a union, and allow you to specify some very small objects of a given number of bits in length. Their

usefulness is limited and they aren't seen in many programs, but we'll deal with them anyway. This example should

help to make things clear:

struct {
/* field 4 bits wide */
unsigned field1 :4;
/*
* unnamed 3 bit field
* unnamed fields allow for padding
*/
unsigned :3;
/*
* one-bit field
* can only be 0 or -1 in two's complement!
*/
signed field2 :1;
/* align next field on a storage unit */
unsigned :0;
unsigned field3 :6;
}full_of_fields;
Each field is accessed and manipulated as if it were an ordinary member of a structure. The keywords signed and

unsigned mean what you would expect, except that it is interesting to note that a 1-bit signed field on a two's

complement machine can only take the values 0 or -1. The declarations are permitted to include the const and

volatile qualifiers.

The main use of bitfields is either to allow tight packing of data or to be able to specify the fields within some

externally produced data files. C gives no guarantee of the ordering of fields within machine words, so if you do

use them for the latter reason, you program will not only be non-portable, it will be compiler-dependent too. The

Standard says that fields are packed into ‘storage units’, which are typically machine words. The packing order, and

whether or not a bitfield may cross a storage unit boundary, are implementation defined. To force alignment to a

storage unit boundary, a zero width field is used before the one that you want to have aligned.

Be careful using them. It can require a surprising amount of run-time code to manipulate these things and you can

end up using more space than they save.

Bit fields do not have addresses—you can't have pointers to them or arrays of them.



最后


了解了这些我想网宿的那道题目也很简单了。希望大家指正。
### C语言的使用方法和特性 #### 定义与声明 在C语言中,是一种特殊的结构体成员,允许程序员指定每个成员占用多少个二进制。这有助于更高效地管理内存资源并精确控制数据表示方式[^1]。 ```c struct bit_field { unsigned int flag : 1; // 占用1 unsigned int value : 7; // 占用7 }; ``` 上述代码片段展示了如何在一个`unsigned int`类型下分配不同的宽度给各个字段。值得注意的是,在某些情况下,编译器可能会根据目标平台的要求自动调整这些置或排列顺序[^4]。 #### 访问成员 一旦定义好带有结构体之后,就可以像处理常规结构体那样对其进行初始化、读取或者修改其中的数据了: ```c struct bit_field example; example.flag = 1; // 设置标志为真 (即 &#39;1&#39;) example.value = 59; // 给value赋值不超过其最大范围内的数值 printf("Flag=%u Value=%u\n", example.flag, example.value); ``` 这段程序说明了怎样创建一个名为 `bit_field` 的实例,并对其内部两个进行了简单操作。由于本质上还是属于某个基本数据类型的子集,因此对于可接受的最大最小值存在限制[^3]。 #### 编译器行为差异 当涉及到不同类型之间组合而成的复杂情况时,不同版本甚至同一款编译工具链也可能表现出不一致的行为模式。比如下面的例子就显示了一个混合字符型(`char`)和整形(`int`)作为基础类型的集合: ```c #include <stdio.h> struct mixed_bits { char a : 2; // 字符串中的两 char b : 3; // 另外三个比特来自同一个字节 int c : 1; // 整形的一跨越到下一个机器字边界上去了... }; int main() { printf("Size of struct mixed_bits is %lu bytes.\n", sizeof(struct mixed_bits)); } ``` 此段代码打印出来的结果会因具体环境而异,因为标准并没有明确规定跨过多个底层单的情况应该如何处理。所以在设计涉及多类型的应用之前应当充分考虑这一点[^2]。 #### 特殊情况下的无名 除了命名好的之外,还可以设置一些未被指派名字的空间来充当间隔作用或是为了满足特定硬件需求所必需留白的地方。这类匿名条目不会参与任何实际运算过程,仅起到占效果而已: ```c struct padding_example { short data : 8; // 实际有用的八信息 short : 6; // 这里预留六个空闲不做他用 short more_data : 2; // 接下来的两置放其他东西 }; ``` 这种做法有时可以帮助开发者更好地匹配外部接口规格或者是优化存储布局以提高性能表现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值