gpt4 book ai didi

c - 访问结构中的位字段

转载 作者:行者123 更新时间:2023-12-04 10:08:22 25 4
gpt4 key购买 nike

我是位域概念的新手。我正在尝试访问结构中的元素,但它在aa=v处显示了这样的错误。

error: incompatible types when assigning to type ‘cc’ from type ‘long unsigned int ’


如果我在 aa= (cc)v;处打字,则显示错误

error: conversion to non-scalar type requested


我试图通过声明一个指向结构的指针来访问元素。在这种情况下,我做得很好,但是在这种情况下,我没有声明指向结构的指针,而必须访问元素。我该如何克服这个错误。

感谢您的任何帮助

#include<stdio.h>
typedef struct
{
unsigned long a:8;
unsigned long b:8;
unsigned long c:8;
unsigned long d:8;
}cc;


int main()
{
cc aa ;
unsigned long v = 1458;
printf("%d\n",sizeof(aa));
aa=v; // aa= (cc)v;
printf("%d %d %d %d\n", aa.a,aa.b,aa.c,aa.d);

return 0;
}

最佳答案

如果打算访问与多种数据类型相同的数据,则需要使用union in C。看看下面的代码片段


写入将其视为32位整数的联合
(然后)
将数据作为4个单独的8位位域返回
(也是很好的措施)
以32位整数的形式再次访问相同的数据




#include<stdio.h>

typedef struct {
unsigned long a:8;
unsigned long b:8;
unsigned long c:8;
unsigned long d:8;
}bitfields;

union data{
unsigned long i;
bitfields bf;
};

int main()
{
union data x;
unsigned long v = 0xaabbccdd;
printf("sizeof x is %dbytes\n",sizeof(x));

/* write to the union treating it as a single integer */
x.i = v;

/* read from the union treating it as a bitfields structure */
printf("%x %x %x %x\n", x.bf.a, x.bf.b, x.bf.c, x.bf.d);

/* read from the union treating it as an integer */
printf("0x%x\n", x.i);

return 0;
}


注意,当union作为整数访问时,系统的字节序确定各个位字段的顺序。因此,在32位x86 PC(小端)上的上述程序将输出:

sizeof x is 4bytes
dd cc bb aa
0xaabbccdd

关于c - 访问结构中的位字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17989483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com