如何为带有位字段的结构分配值? [英] How to assign value to a struct with bit-fields?
问题描述
我有一个位域(总共32位宽)的结构,我有一个32位的变量。当我尝试分配变量值到我的结构,我得到一个错误:
I have a struct with bit-fields (totally 32 bit width) and I have a 32-bit variable. When I try to assign the variable value to my struct, I got an error:
错误:从'uint32_t {aka unsigned int} '到非标量类型'main():: CPUID'请求。
error: conversion from ‘uint32_t {aka unsigned int}’ to non-scalar type ‘main()::CPUID’ requested.
struct CPUIDregs
{
uint32_t EAXBuf;
};
CPUIDregs CPUIDregsoutput;
int main () {
struct CPUID
{
uint32_t Stepping : 4;
uint32_t Model : 4;
uint32_t FamilyID : 4;
uint32_t Type : 2;
uint32_t Reserved1 : 2;
uint32_t ExtendedModel : 4;
uint32_t ExtendedFamilyID : 8;
uint32_t Reserved2 : 4;
};
CPUID CPUIDoutput = CPUIDregsoutput.EAXBuf;
你有什么想法如何以最短的方式做?感谢
Do you have any idea how to do it in the shortest way? Thanks
当然,我在实际代码中有更适当的EAX值,但我想这不会影响这里。
P.S. Of course I have more appropriate value of EAX in real code, but I guess it doesn't affect here.
推荐答案
从不依赖于编译器如何在内存中布局您的结构。
You should never rely on how the compiler lays out your structure in memory. There are ways to do what you want with a single assignment, but I will neither recommend nor tell you.
完成作业的最佳方式如下:
The best way to do the assignment would be the following:
static inline void to_id(struct CPUid *id, uint32_t value)
{
id->Stepping = value & 0xf;
id->Model = (value & (0xf << 4)) >> 4;
id->FamilyID = (value & (0xf << 8)) >> 8;
id->Type = (value & (0x3 << 12)) >> 12;
id->Reserved1 = (value & (0x3 << 14)) >> 14;
id->ExtendedModel = (value & (0xf << 16)) >> 16;
id->ExtendedFamilyID = (value & (0xff << 20)) >> 20;
id->Reserved2 = (value & (0xf << 28)) >> 28;
}
相反
static inline uint32_t from_id(struct CPUid *id)
{
return id->Stepping
+ ((uint32_t)id->Model << 4)
+ ((uint32_t)id->FamilyID << 8)
+ ((uint32_t)id->Type << 12)
+ ((uint32_t)id->Reserved1 << 14)
+ ((uint32_t)id->ExtendedModel << 16)
+ ((uint32_t)id->ExtendedFamilyID << 20)
+ ((uint32_t)id->Reserved2 << 28);
}
这篇关于如何为带有位字段的结构分配值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!