I don't know how to pass a value to the bitfield:
- in header file I have the struct definition below:
typedef struct { boolean Error; } Struct_A_T;
Struct_A_T Struct_A = {0U};
boolean WriteValue;
if (TRUE) {
Struct_A.Error.index = WriteValue;
}
}
else {
index ;
}
As you can see, the index will increment, I want the WriteValue to pass a value to the bit location equal to index for Struct_A_Error. I don't know how should I define this and make the bit as flexible so index can control the bit location. Thanks
expect to have bit location update to the value of index
CodePudding user response:
expect to have bit location update to the value of index
That's not how bitfields work. That's impossible in C.
Types in C are static. They can't be changed at runtime – so your bitfield must always be in the same position.
If you need to set a specific bit in a memory location, you will have to put an integer there, and use bit shifts and logical operators to put the bit where you want it.
CodePudding user response:
As I see it, OP does not want a bit-field or bool
struct
member, yet a simply unsigned.
#include <stdbool.h>
typedef struct {
unsigned Error;
} Struct_A_T;
Struct_A_T Struct_A = {0U};
...
bool WriteValue;
...
if (TRUE) {
unsigned mask = 1u << index;
if (WriteValue) Struct_A |= mask;
else Struct_A &= ~mask;
}
...
index
should be less than an unsigned
bit-width (typically 32).