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

Typedef union problem

Hello! I have a typedef union and variable:

typedef union int2char{unsigned char high_byte;
                       unsigned char low_byte;
                       unsigned int  int_byte;
                      } int2char;

int2char dac_value;


When i assign

dac_value.int_byte = 0xAAAA;


i have

dac_value.int_byte = 0xAAAA;
dac_value.low_byte = 0xAA;
dac_value.high_byte = 0xAA;


but when i assign,example,0xFF05

dac_value .int_byte = 0xFF05;
dac_value.low_byte =0xFF;
dac_value.high_byte = 0xFF;


same results are obtained when i assign,example,0x1005

dac_value .int_byte = 0x1005;
dac_value.low_byte =0x10;
dac_value.high_byte = 0x10;


I can not understand where the error and why??
thanks for the help!.

Parents
  • What do you think happens in a union?

    What is the address of your low_byte member?
    What is the address of your high_byte member?
    What is the address of your int_byte member.

    By the way - what is "int byte"?

    You have to use a struct to encapsulate your low_byte and high_byte members to have them stored after each other, and not on top of each other.

    By the way - how many threads do you think you can find on this forum that describes problems with using unions for type conversion? A union was added to the standard to allow the same memory space to store _either_ of multiple data types. The standard does not guarantee that you can write to one member and read back reasonable data from another member. All that is covered is the start offset of the members.

    What do you think happens when you switch from a compiler that stores an int low-byte before high-byte compared to a compiler that stores an int high-byte before low-byte?

Reply
  • What do you think happens in a union?

    What is the address of your low_byte member?
    What is the address of your high_byte member?
    What is the address of your int_byte member.

    By the way - what is "int byte"?

    You have to use a struct to encapsulate your low_byte and high_byte members to have them stored after each other, and not on top of each other.

    By the way - how many threads do you think you can find on this forum that describes problems with using unions for type conversion? A union was added to the standard to allow the same memory space to store _either_ of multiple data types. The standard does not guarantee that you can write to one member and read back reasonable data from another member. All that is covered is the start offset of the members.

    What do you think happens when you switch from a compiler that stores an int low-byte before high-byte compared to a compiler that stores an int high-byte before low-byte?

Children