Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

bit fields - C++ 2-bit bitfield arrays possible?

I have a struct of 2-bit bitfields like this:

struct MyStruct {
    unsigned __int32 info0  : 2;
    unsigned __int32 info1  : 2;
    unsigned __int32 info2  : 2;
   ...
    unsigned __int32 info59 : 2;
};

And another like this going up to 120... Is there a way to write and address them as an array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you can't use Paul R's answer for whatever reason, you can always use a custom accessor with a standard array :

static unsigned __int8 infos[30]; // 240 bits allocated

unsigned __int8 getInfo( unsigned short id_num )
{
    return (infos[id_num/4] >> ((2*id_num) % 8) ) & 0x3;
}
// setInfo left as an exercise.

(You may need to check the logic here, I haven't tested it.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...