View previous topic :: View next topic |
Author |
Message |
cfernandez
Joined: 18 Oct 2003 Posts: 145
|
How to store value a Structure ??? |
Posted: Sat Mar 25, 2006 12:10 pm |
|
|
Hi,
I have the following struct
Code: | struct stDef
{
int a : 3;
int b : 1;
int c : 4;
int d : 2;
int e : 1;
int f : 5;
};
union
{
struct stDef stA;
char sData[ 2 ];
} uB;
////////////////////////////////////////////////////////////////////////////
//
// Main
//
////////////////////////////////////////////////////////////////////////////
void main()
{
uB.stA.a = 2;
uB.stA..b = 1;
uB.stA..c = 3;
uB.stA..d = 1;
uB.stA..e = 0;
uB.stA..f = 15;
fprintf( SERIAL_2, "stA: %u %u %u %u %u %u\n\r", uB.stA.a, uB.stA.b, uB.stA.c, uB.stA.d, uB.stA.e, uB.stA.f );
fprintf( SERIAL_2, "Data: %02X %02X\n\r", uB.sData[0], uB.sData[1] );
}
|
The output for this is:
stA: 2 1 3 1 0 15
Data: 3A 79
If I put the bits values of stA into the 2 bytes the correct value is 0x53 0x4F.
How to store the value the union or struct???
Thanks |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Sat Mar 25, 2006 1:51 pm |
|
|
Quote: | The output for this is:
stA: 2 1 3 1 0 15
Data: 3A 79
If I put the bits values of stA into the 2 bytes the correct value is 0x53 0x4F. |
The correct values for your code are 0x3A and 0x79.
The following charts show the size of the bitfields with "xxxx"
and the values that you put into them with "0011", etc.
Code: |
c b a bitfield names
xxxx x xxx bitfield widths
0011 1 010 binary values inserted into bitfields
3 1 2 decimal values inserted into bitfields
result = 0b00111010 = 0x3A
----------------------------
f e d
xxxxx x xx
01111 0 01
15 0 1
result = 0b01111001 = 0x79
|
I think your problem is caused by two beliefs:
1. You think the structure is defined with the MSB bits coming first.
2. You think that any zero bits on the end of a byte are thrown away
and the result is then justified.
Both of those beliefs are wrong.
The "a" bitfield is the lowest field in the first byte. The "d" bitfield is
the lowest field in the 2nd byte. Also, all bit positions are maintained.
No zeros bits are thrown away. No adjustment of the bit positions is
done. The compiler will create the bitfields exactly as you have
defined them. |
|
|
cfernandez
Joined: 18 Oct 2003 Posts: 145
|
|
Posted: Sat Mar 25, 2006 2:31 pm |
|
|
PCM,
Thank you very much!!!!, What is the best way for transform 53 to 3A and 4F to 79???. In my appl. my customer send me 0x53 0x4F
Thank you very much!! |
|
|
cfernandez
Joined: 18 Oct 2003 Posts: 145
|
|
Posted: Sat Mar 25, 2006 8:40 pm |
|
|
I have a simple solution, I define my struct with the fields in order to the bitfields. Work!
Thank you for help me!! |
|
|
|