Chinaunix
标题:
C语言位域实现相关的一个问题?
[打印本页]
作者:
hitcser01
时间:
2014-08-24 22:31
标题:
C语言位域实现相关的一个问题?
本帖最后由 hitcser01 于 2014-08-24 22:33 编辑
查了一下资料,只找到讲怎么用的,没找到讲为什么的。可能是我搜索的姿势不对
我这里是x86 32位 Linux, GCC 4.7.3, GDB 7.6.2
代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
struct bitfield{
int a:2;
int b:1;
};
int main(void)
{
struct bitfield bf;
memset(&bf, 0, 4);
bf.a=3;
bf.b=1;
printf("%d\t%d\n", bf.a, bf.b);
return 0;
}
复制代码
输出:
-1 -1
复制代码
gdb调试:
(gdb) x/tb &bf
0xbfffeb8c: 00000111
复制代码
结果为什么是 -1 呢?
更一般地,编译器是以什么规则解析了哪一个内存区域,得到的结果?
谢谢。
作者:
hellioncu
时间:
2014-08-24 22:35
符号位为1就是认为负数。改成
struct bitfield{
unsigned int a : 2;
unsigned int b : 1;
};
就行了
作者:
hitcser01
时间:
2014-08-24 22:41
本帖最后由 hitcser01 于 2014-08-24 22:52 编辑
回复
2#
hellioncu
谢谢您 :wink:
还有一个问题,
在
struct bitfield{
int a:2;
int b:1;
};
复制代码
中,
bf.b 所引用的内存位串是什么呢?(通俗一点表达,就是 bf.b 的位模式是怎样的?)
表达能力着急,我的意思其实是,能不能详细说下bf.b的值是怎样算出来的,声明 int b:1 ,但能以 %d 打印,说明应该是取了 32bit 来以int格式解析的,那个 32bit 是怎么由 int b:1占有的 1bit 生成的?
作者:
ahui886
时间:
2014-08-28 10:01
回复
3#
hitcser01
自己运行,看结果吧
#include <stdio.h>
typedef union test_tag
{
struct bitfield
{
int a:2;
int b:1;
} bits;
int word;
} test_t;
int main(void)
{
test_t test;
test.word = 0;
test.bits.a = 2;
test.bits.b = 1;
printf("0x%08X", test.word);
return 0;
}
复制代码
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2