cancel
Showing results for 
Search instead for 
Did you mean: 

How to use a Union to access and change the bits?

LVasc.1
Associate II

My header file:

typedef union {

  struct {

    uint8_t u_bit1:1;

    uint8_t u_bit2:1;

    uint8_t u_bit3:1;

    uint8_t u_bit4:1;

    uint8_t u_bit5:1;

    uint8_t u_bit6:1;

    uint8_t u_bit7:1;

    uint8_t u_bit8:1;

  } bits;

} u_serialSequenceBits;

My .c file:

u_serialSequenceBits myUnion;

myUnion.bits.u_bit2 = 1;

myUnion.bits.u_bit5 = 0;

The Errors:

Description Resource Path Location Type

expected '=', ',', ';', 'asm' or '__attribute__' before '.' token ihm.c /base_UPS_G070v2/Core/Src line 29 C/C++ Problem

Because this commands:

myUnion.bits.u_bit2 = 1;

and

myUnion.bits.u_bit5 = 0;

1 ACCEPTED SOLUTION

Accepted Solutions
Nikita91
Lead II

GCC is "Gnu C Compiler", the compiler used by STM32CubeIDE 

In C instructions must be inside a function:

void function (void)
{
    myUnion.bits.u_bit2 = 1;
    myUnion.bits.u_bit5 = 0;
}

If you want to initialize the struct at the declaration:

u_serialSequenceBits myUnion =
{
	.bits.u_bit2 = 1,
	.bits.u_bit5 = 0,
};

Pretty much everything related to bit-fields in the C standard is poorly defined. Typically, you will not find anything explicitly addressing the behavior of bit fields, but their behavior is rather specified implicitly, "between the lines". This is why you should avoid using bit fields.

View solution in original post

4 REPLIES 4
Nikita91
Lead II

I don't get error when I compile your code with GCC

Did you put

myUnion.bits.u_bit2 = 1;
myUnion.bits.u_bit5 = 0;

inside a function ?

Show your code around line 29

LVasc.1
Associate II

No. It's just inside the source file ".c".

Sorry, i'm a beginner. What's GCC? I'm usign the STM32CubeIDE software.

Nikita91
Lead II

GCC is "Gnu C Compiler", the compiler used by STM32CubeIDE 

In C instructions must be inside a function:

void function (void)
{
    myUnion.bits.u_bit2 = 1;
    myUnion.bits.u_bit5 = 0;
}

If you want to initialize the struct at the declaration:

u_serialSequenceBits myUnion =
{
	.bits.u_bit2 = 1,
	.bits.u_bit5 = 0,
};

Pretty much everything related to bit-fields in the C standard is poorly defined. Typically, you will not find anything explicitly addressing the behavior of bit fields, but their behavior is rather specified implicitly, "between the lines". This is why you should avoid using bit fields.

LVasc.1
Associate II

It worked, Thanks!

The use of union on my project it's because i want to send a serial data to a 74hc595 and give the manager to change the bits in others .c files.