This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Struct in union

Hi
I have some problems with struct inside a union
This is my code.

union{
	unsigned char id_byte[2];

	struct {
			unsigned char DLC:4;
			unsigned char RTR:1;
			unsigned int identifier:11;
			}del_element;
}can_descriptor;

when I write an_descriptor.del_element.identifier=0x0A;

nothing comes in id_byte array why?
The values I put in DLC and RTR are placed correct.

If i change the code to
union{
	unsigned char id_byte[2];

	struct {
			unsigned int identifier:11;
			unsigned char DLC:4;
			unsigned char RTR:1;
			}del_element;
}can_descriptor;
And writes 0x0A to identifier:
id_byte[0]=0
id_byte[1]=0x0A

but i shoud be
id_byte[0]=0x80
id_byte[1]=0x01

why?
This program is part of an CAN program for SJA1000, this funktion i made make it easy to write the CAN iddentifiers DLC and RTR bit in the controller.....if it worked.

Best Regrads
Soren

Parents
  • Keil C has a somewhat non-intuitive order for bitfields.

    http://www.keil.com/support/docs/1948.htm

    Per the C standard, the "correct" storage pattern for bitfields is up the implementation. A program cannot rely on the order of bitfields within an int, nor can it depend on the signed-ness of a bitfield. For that matter, per spec all bitfields must occupy an "int" (whatever that may be), though every compiler I've ever used lets you specify other byte widths for them.

    In fact, I avoid using this C feature at all because the results are so different for every compiler and platform. In addition, many compilers generate poor code for bitfields. It's more portable and often more efficient just to use the & and | operators directly. If you're sending messages to another processor, you can use the same declarations without worrying about different implementation orders.

Reply
  • Keil C has a somewhat non-intuitive order for bitfields.

    http://www.keil.com/support/docs/1948.htm

    Per the C standard, the "correct" storage pattern for bitfields is up the implementation. A program cannot rely on the order of bitfields within an int, nor can it depend on the signed-ness of a bitfield. For that matter, per spec all bitfields must occupy an "int" (whatever that may be), though every compiler I've ever used lets you specify other byte widths for them.

    In fact, I avoid using this C feature at all because the results are so different for every compiler and platform. In addition, many compilers generate poor code for bitfields. It's more portable and often more efficient just to use the & and | operators directly. If you're sending messages to another processor, you can use the same declarations without worrying about different implementation orders.

Children