1

I have a struct defined as:

typedef struct {
   uint8_t field1 : 6,
   uint8_t field2 : 1,
   uint8_t field3 : 1
} myStruct;

and then:

myStruct s;

What is a safe way to assign an 8-bit value to all the fields at once, i.e.:

s = 10;

The compiler gives error when trying to assign like this (obviously, I'm not even implying this is the way to do it :) ).

Would this be recommended:

uint8_t a = 10;
s = * ((myStruct*) &a);

?

Bogdan Alexandru
  • 5,394
  • 6
  • 34
  • 54

2 Answers2

2

You can use a union:

union myUnion {
  struct myStruct ms;
  uint8_t byte;
};

myUnion u;
u.byte = 10;  /* Uses the same memory as myStruct and its fields. */
printf("field1=%u field2=%u field3=%u\n", u.ms.field1, u.ms.field2, u.ms.field3);

This used to be frowned upon, but see @mafso's comment below, it seems to be allowed now.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
  • 1
    ... but compilers support it and it's the intent of the standard to allow it. There was a footnote added to 6.5.2.3 p3 "If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called 'type punning'). This might be a trap representation." Cf. [DR 283](http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_283.htm) – mafso Aug 19 '14 at 12:59
0

you can't assign values to the structure elements like this-

myStruct s;
s = 10;

It is Not allowed. It is not a correct way to do the things!

When you do like below-

uint8_t a = 10;
s = * ((myStruct*) &a);

It is not a safe way to allocate the value 10 to the bit field members! So do it individually like-

s.field1=xx; // Instead of xx, yy and zz assign values
s.field2=yy;
s.field3=zz;

It is the best way to do it!

Sathish
  • 3,740
  • 1
  • 17
  • 28
  • -1. If the structure is padded, the above will cause sparks to fly. – unwind Aug 19 '14 at 13:04
  • @unwind I think that if OP uses bit fields, he already knows what he is doing, and can be sure there are no issues of padding, bit order, strict aliasing, etc – anatolyg Aug 19 '14 at 13:10