我有一个结构变量,如下所示。(我已经更改了变量名,因此它们没有意义。)我在初始化myStruct1数组的位时遇到问题。
我需要初始化myStruct1.id.lengthOfData
例如40和numberOfBits.number
= 16。为此,我尝试使用memset等,但我不能正确地做到这一点。我怎么能这样做而不是手动做?提前谢谢。
#define unsigned int INT32U
typedef struct{
struct{
INT32U lengthOfData :16;
INT32U command :8;
INT32U sendBack :1;
INT32U backTest :1;
INT32U required :1;
INT32U reserved :5;
INT32U student_class_id ;
}id;
union{
INT32U number;
struct{
INT32U firstFiveBits:5;
INT32U secondFiveBits:5;
INT32U thirdFiveBits :5; INT32U eightBits :8;
INT32U secondEightBits :8;
INT32U restOfit:1;
}numberOfbits;
}foo;
union{
INT32U numberTwo;
struct{
INT16U firstSteenBits:16;
INT16U secondSteenBits :16;
}bits;
}myUnion;
}myStruct1;
修改
这是我到目前为止所做的。
myStruct1 *myPtr;
myPtr = new myStruct1;
memset((myPtr), 0, sizeof(*myPtr)); // to zeros for all bits of myStruct1
memset((myPtr), 3,1); // to give 3 to lengthOfData.
答案 0 :(得分:0)
由于您正在处理位字段,您可以使用它们并将它们初始化为普通的struct字段
#include <iostream>
using namespace std;
#define INT32U unsigned int
#define INT16U unsigned short
typedef struct{
struct{
INT32U lengthOfData :16;
INT32U command :8;
INT32U sendBack :1;
INT32U backTest :1;
INT32U required :1;
INT32U reserved :5;
INT32U student_class_id ;
}id;
union{
INT32U number;
struct{
INT32U firstFiveBits:5;
INT32U secondFiveBits:5;
INT32U thirdFiveBits :5; INT32U eightBits :8;
INT32U secondEightBits :8;
INT32U restOfit:1;
}numberOfbits;
}foo;
union{
INT32U numberTwo;
struct{
INT16U firstSteenBits:16;
INT16U secondSteenBits :16;
}bits;
}myUnion;
}myStruct1;
int main() {
myStruct1 obj;
obj.id.required = 1; // Make sure not to exceed the bit capacity
obj.id.lengthOfData = 22; // Make sure not to exceed the bit capacity
cout << obj.id.lengthOfData << endl;
cout << obj.id.required << endl;
obj.id.required = 0;
cout << obj.id.required << endl;
return 0;
}
请确保不要超过位字段本身的容量,并且不要依赖字段的顺序为单个机器字