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 Reply Children
  • if I shifts, I need more code, becourse I need to shift different if i have a RTR bit set.

    I rather strongly suspect the opposite to be true. If the shift is, indeed, different depending on the status of some bits, that's impossible to model using bitfields alone, because the lengths, and thus by implication the positions, of bitfields inside a struct are fixed at compile time.
    It's much more transparent to have the argument of a shift operator be a variable or expression than having to do something like

    if(rtr)
       my_union.rtr_set.somebit = 1;
    else
       my_union.rtr_clr.somebit = 1;
    

  • "if I shifts, I need more code ... I don't have that problem in union struct."

    It may look like more source code, but have you checked the generated object code?

    Does it make any difference to the amount of code that the processor actually has to run?

  • year ok.

    yes as small as passebel, no time to waste.

    You say that i shoud use mask and shift?
    dose't it give more code?



    Soren

  • "You say that i shoud use mask and shift?
    dose't it give more code?"


    Try re-reading the previous posts!

    Here's a reminder of what's been said so far:

    "many compilers generate poor code for bitfields. It's more portable and often more efficient just to use the & and | operators directly."

    "I don't think there's any reason to believe that bitfields will give you (significantly) better code than shifts and masks and some bitfield implementations are notoriously inefficient - so shifts and masks can actually be better!"

    "[shift & mask] is probably how the compiler actually implements the bitfields!"

    That should answer your question!

    And again, shifts & masks are portable; bitfields are not.