使用C中的一个位字段时字段顺序 [英] Order of fields when using a bit field in C

查看:154
本文介绍了使用C中的一个位字段时字段顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类型的结构

typedef struct
{
unsigned int a : 8;
unsigned int b : 6;
unsigned int c : 2;
}x, *ptr;

我想什么做的,就是改变场c的值。

What i would like to do, is change the value of field c.

我像做以下

x structure = { 0 };
x->c = 1;

当我看着存储器映射,我希望找到的 00 01 的,而是我觉得 00 40 的。
它看起来像安排第二个字节时,提出的 C 的最低位字段的的领域中的最高位。我已经看到了这个对GCC和Windows编译器。

When I look at the memory map, I expect to find 00 01, but instead I find 00 40. It looks like when arranging the second byte, it puts c field in the lowest bits and b field in the highest bits. I've seen this on both GCC and Windows compilers.

现在,我要做的就是以下,这是工作确定。

For now, what I do is the following, which is working OK.

unsigned char ptr2 = (unsigned char*) ptr
*(ptr2 + 1)  &= 0xFC
*(ptr2 + 1)  |= 0x01

我是不是在看内存映射错了吗?
谢谢你的帮助。

Am I looking at the memory map wrong? Thank you for your help.

推荐答案

C标准允许编译器将位字段中的任何命令。没有可靠和便携的方式来确定顺序。

C standard allows compiler to put bit-fields in any order. There is not reliable and portable way to determine the order.

如果你需要知道确切的位位置,最好是使用普通无符号的变量和位掩码。

If you need to know the exact bit positions, it is better use plain unsigned variable and bit masking.

编辑:

下面是一个可能的替代使用位字段。

Here's one possible alternative to using bit-fields.

#include <stdio.h>

#define MASK_A    0x00FF
#define MASK_B    0x3F00
#define MASK_C    0xC000
#define SHIFT_A   0
#define SHIFT_B   8
#define SHIFT_C   14

unsigned GetField(unsigned all, unsigned mask, unsigned shift)
{
    return (all & mask) >> shift;
}

unsigned SetField(unsigned all, unsigned mask, unsigned shift, unsigned value)
{
    return (all & ~mask) | ((value << shift) & mask);
}

unsigned GetA(unsigned all)
{
    return GetField(all, MASK_A, SHIFT_A);
}

unsigned SetA(unsigned all, unsigned value)
{
    return SetField(all, MASK_A, SHIFT_A, value);
}

/* Similar functions for B and C here */

int main(void)
{
    unsigned myABC = 0;
    myABC = SetA(myABC, 3);
    printf("%u", GetA(myABC)); // Prints 3
}

这篇关于使用C中的一个位字段时字段顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆