我在c中有这样的结构
struct RegisterStruct
{
uint64_t b_0 : 64;
uint64_t b_1 : 64;
uint64_t c_0 : 64;
uint64_t c_1 : 64;
uint64_t c_2 : 64;
uint64_t d_0 : 64;
uint64_t d_1 : 64;
};
我想将字段连接成一个uint64_t
整数。每个字段应占据给定数量的位,定义如下:
b_0: 4bits
b_1: 4bits
c_0: 8bits
c_1: 8bits
c_2: 8bits
d_1: 16bits
d_2: 16bits
结果应该是一个uint64_t
整数,其中包含连接的位域(从b_0
到d_2
),每个位域占据给定的位数。
这是我尝试过的,但我认为此解决方案不正确:
struct RegisterStruct Register;
Register.b_0 = 8;
Register.b_1 = 8;
Register.c_0 = 128;
Register.c_1 = 128;
Register.c_2 = 128;
Register.d_0 = 32768;
Register.d_1 = 32768;
uint64_t reg_frame =Register.b_0<<60|Register.b_1<<56|Register.c_0<<48|Register.c_1<<40|Register.c_2<<32|Register.d_0<<16|Register.d_1;
typedef union
{
struct
{
uint64_t b_0 : 4;
uint64_t b_1 : 4;
uint64_t c_0 : 8;
uint64_t c_1 : 8;
uint64_t c_2 : 8;
uint64_t d_0 : 16;
uint64_t d_1 : 16;
};
uint64_t u64;
}R_t;
int main()
{
R_t Register;
Register.b_0 = 8;
Register.b_1 = 8;
Register.c_0 = 128;
Register.c_1 = 128;
Register.c_2 = 128;
Register.d_0 = 32768;
Register.d_1 = 32768;
printf("%llx\n", (long long unsigned)Register.u64);
}