2009-04-06 01:12 AM
how to use the bit fields structure?
2011-05-17 04:08 AM - last edited on 2024-03-05 05:41 AM by Peter BENSCH
Posted on May 17, 2011 at 13:08
Hi all;
Thanks for your advices. I solved my problem! (I'm using IAR)
I tried to use the two methods proposed by andreas1 and janek. The two methods work as I want. But I think using union is an elegant way to solve the problem. I share it:
typedef union
{
struct
{
u8 a : 1;
u8 b : 1;
u8 c : 2;
u8 d : 3;
u8 e : 1;
} fields;
vu8 REG;
} REG_struct;
REG_struct SPI_DATA;
vu8 var;
SPI_DATA.REG = 0x55;
printf(''sizeof(REG_struct) = % d\n'', sizeof(REG_struct));
printf(''SPI_DATA.REG = 0x % x,
SPI_DATA.a = 0x % x,
SPI_DATA.b = 0x % x,
SPI_DATA.c = 0x % x,
SPI_DATA.d = 0x % x,
SPI_DATA.e = 0x % x\n'',
SPI_DATA.REG,
SPI_DATA.fields.a,
SPI_DATA.fields.b,
SPI_DATA.fields.c,
SPI_DATA.fields.d,
SPI_DATA.fields.e);
SPI_DATA.REG = 2;
printf(''SPI_DATA.REG = 0x % x,
SPI_DATA.a = 0x % x,
SPI_DATA.b = 0x % x,
SPI_DATA.c = 0x % x,
SPI_DATA.d = 0x % x,
SPI_DATA.e = 0x % x\n'',
SPI_DATA.REG,
SPI_DATA.fields.a,
SPI_DATA.fields.b,
SPI_DATA.fields.c,
SPI_DATA.fields.d,
SPI_DATA.fields.e);
SPI_DATA.fields.a = 1;
SPI_DATA.fields.d = 1;
printf(''SPI_DATA.REG = 0x % x,
SPI_DATA.a = 0x % x,
SPI_DATA.b = 0x % x,
SPI_DATA.c = 0x % x,
SPI_DATA.d = 0x % x,
SPI_DATA.e = 0x % x\n'',
SPI_DATA.REG,
SPI_DATA.fields.a,
SPI_DATA.fields.b,
SPI_DATA.fields.c,
SPI_DATA.fields.d,
SPI_DATA.fields.e);
var = SPI_DATA.REG;
printf(''var = 0x % x\n'', var);
SPI_I2S_SendData(SPI1, SPI_DATA.REG);
//////////////////////////////////////////////////
The output of the program is:
sizeof(REG_struct) = 1
SPI_DATA.REG = 0x55, SPI_DATA.a = 0x1, SPI_DATA.b = 0x0, SPI_DATA.c = 0x1, SPI_DATA.d = 0x5, SPI_DATA.e = 0x0
SPI_DATA.REG = 0x2, SPI_DATA.a = 0x0, SPI_DATA.b = 0x1, SPI_DATA.c = 0x0, SPI_DATA.d = 0x0, SPI_DATA.e = 0x0
SPI_DATA.REG = 0x13, SPI_DATA.a = 0x1, SPI_DATA.b = 0x1, SPI_DATA.c = 0x0, SPI_DATA.d = 0x1, SPI_DATA.e = 0x0
var = 0x13
//////////////////////////////////////////////////
I'm wondering if using this method is optimized vs using the masks and the shifts (timnig/size)?
cheers
2011-05-17 04:08 AM
Quote:
I'm wondering if using this method is optimized vs using the masks and the shifts (timnig/size)?
I wouldn't expect to see a lot of difference, but there's only one way to be sure...2011-05-17 04:08 AM
Quote:
I'm wondering if using this method is optimized vs using the masks and the shifts (timnig/size)?
Quote:
I wouldn't expect to see a lot of difference, but there's only one way to be sure...
I have certainly seen cases where the bitfield implementation was less efficient than just coding the shifts & masks ''manually''! :( Again: you know exactly where you are with shifts & masks - why introduce any doubt or uncertainty?! :o