This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

constant bit-fields in struct

Hi All,,

How can i declare constant bit fields in a struct ??

struct mystruct{
unsigned char xx:6;
unsigned char yy:2;
}mystruct;

Let us say i want mystruct.yy to be a constant 00, how can i do that ??

mystruct must be a 8-bit datatype. which of its two components xx and yy would be at MSB ?? If anyone can tell how to figure that out it would be great.

Thankzz && Bye
-Rocknmoon

Parents
  • You declare constant structure members the same way you declare constant variables:

    struct mystruct {
       unsigned char xx:6;
       unsigned char const yy:2;
    } mystruct = { 3, 0 };
    
    Note that you have to initialize mystruct because later the compiler will not let you modify the constant yy field. Of course you can cheat and use typecast to modify yy:
    (unsigned char)mystuct.yy = 1;
    
    But if you do that, what's the point in having a constant struct member?
    Which of the structure members are MSB or LSB you can find out by testing the code. Bit-fields are implementation specific. Here is one of possible tests:
    mystruct = { 0, 1 };
    printf("LSB=%d", (1 & *(char*)&mystruct) + '0');
    
    - Mike

Reply
  • You declare constant structure members the same way you declare constant variables:

    struct mystruct {
       unsigned char xx:6;
       unsigned char const yy:2;
    } mystruct = { 3, 0 };
    
    Note that you have to initialize mystruct because later the compiler will not let you modify the constant yy field. Of course you can cheat and use typecast to modify yy:
    (unsigned char)mystuct.yy = 1;
    
    But if you do that, what's the point in having a constant struct member?
    Which of the structure members are MSB or LSB you can find out by testing the code. Bit-fields are implementation specific. Here is one of possible tests:
    mystruct = { 0, 1 };
    printf("LSB=%d", (1 & *(char*)&mystruct) + '0');
    
    - Mike

Children