开发者

Removing Bit fields in a struct

I have a question. I have a legacy application which used bit fields in a structure. Something like this

struct sample
{
    BYTE            one: 2; 
    BYTE            two     : 1;
    BYTE            three: 5;
} sampletest;

So three can have a value of MAX 31 only.

Now I have a requirement to increase the MAX value of three. I am planning t开发者_Python百科o remove the bit fields. It will handle more memory now. Apart from this, Is there anything that I need to take care? Does it cause any more other harm?


If BYTE is an unsigned type, then the bitfields will have well-defined overflow behavour - eg:

sampletest.one = -1;

will set sampletest.one to 3. This behaviour will change if you make it a wider type.


You have to carefully look through all the code to check that the code doesn't rely on this structure containing bit fields.

For example it could be that somewhere in the code the whole byte could be read, manipulated and written back (with casts it's not a problem) - if you remove bit fields this code will break apart. So look for casts - they are the indicator of code to check.


There are a few additional things that might be important for you. Or not.

In C language bit fields can only be declared as 'int', 'signed int' or 'unsigned int' (also 'bool' in C99). Any other type is not allowed (or not portable, if your compiler allows it as an extension). (I wonder what hides behind 'BYTE' in your case.)

Also, type 'int' (not explicitly 'signed' or 'unsigned'), when used in a bit-field declaration, might declare either signed or unsigned field, depending on the implementation (and/or its compilation settings).

Since you are planning to convert your 'three' into a ordinary field (not a bit-filed), it might make sense to check whether it was supposed to be signed or unsigned.


As it's declared, assuming #define BYTE unsigned char in a header file somewhere, your struct is taking just one byte's worth of space if the compiler is packing the fields nicely. If the code only accesses the fields within the struct and never tries to copy/zero the struct as a whole assuming it's just one byte in size (e.g. no sizeof struct sampletest involved), you'll be fine. It should also be a fairly simple matter to dig through the code and examine every place where it's touched just to make sure, not to mention running the system through its test cycle after you've made your change.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜