Alex
Alex

Reputation: 10126

Should be casting used for setting a bitfield?

Let's suppose, I have a following structure:

struct my_struct {
    uint32_t bf1 : 3;
    uint32_t bf2 : 5;
    uint32_t bf3 : 16;
    uint32_t bf4 : 8;
};

and the following enum:

enum bf1_values {
     Val1 = 0x0;
     Val2 = 0x4;
     Val3 = 0x7;
};

in addition, getter and setter functions for bf1:

uint32_t bf1_getter() {
    return global_struct.bf1; // cast value to (uint32_t)?
}


void bf1_setter(enum bf1_values val) {
    global_struct.bf1 = val; // cast enum to (uint32_t)?
}

Should I use the typecasting in getter and setter functions for safety?

EDIT:

The structure is supposed to be sent to HW.

EDIT2:

What I want to achieve is to be really sure that enum will be correctly written to a bitfield, and correctly read from bitfield.

Upvotes: 1

Views: 1373

Answers (1)

Christoph
Christoph

Reputation: 169703

No need for casting here - the assignments are already 'safe' insofar as a conforming implementation shouldn't corrupt other members. Assuming normal integer overflow semantics apply, the only problematic case is signed overflow, which may raise a signal (but I'm hard pressed to see that happening in practice if the bit field width is smaller than a full word as harware support for overflow detection will be lacking) and is otherwise implementation-defined. This caveat does not apply to your example as the target types are unsigned.

Keep in mind that bit field semantics are largely implementation-defined - even using a type other than int is actually a language extension - and it's up to you to check that the compiler does what you expect it to do on all relevant platforms.

A more portable but also less convenient approach would be to just use an uint32_t and do the bit fiddling manually. IF you don't need that protability, it should be fine as-is.

Upvotes: 2

Related Questions