Thread: Unions and bytes

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    3

    Unions and bytes

    I'm not sure how to go about utilizing a union to hold the information I need.

    The union is set up as follows:

    union
    {
    struct
    {
    float val_1;
    float val_2;
    } Struct_Words;

    struct
    {
    unsigned char pad3[3];
    unsigned char val_3;
    unsigned char pad4[4];
    } Struct_Bytes;

    } Data;

    What I ulitmately need to do is to store the val_3 byte into the LS Byte (big endian architecture) of val_2, after val_2 has been determined.

    Then, I need to write the data (I'm assuming 8-bytes total for the 'Words' structure) to a binary file.

    Any thoughts on how to accomplish this, alternate approaches, etc.?

    Thanks for any ideas!!

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    union u
    {
        struct
        {
            float f1;
            float f2;
        } f;
        unsigned char bytes[8];
    };
    ;
    union u unie;
    unie.f.f2 = 1.2345;
    unie.bytes[3] = unie.bytes[7];

    Presto chango!

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Mar 2003
    Posts
    3
    Thanks for your response! I just want to see if I understand what you sent.

    After unie.bytes[7] is determined, I can save 3 bits of that byte into unie.bytes[3]?

    Is this in effect also storing this information into unie.f.f2?

    To write the union data to a binary file, do I just fwrite the union itself (after all of the union variables have been calculated), and I will have the data for all three data types stored?

    How do I verify my data from this variable (i.e. for unie.f.f2, what kind of print statement format do I need to verify the two pieces of information stored)?

    Essentially, the object was to utilize one of the float types to contain data from two variables (f2 and bytes in your example). I just wanted to make sure I understood you correctly, or get straightened out if I didn't.

    Thanks for your help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Double's and floats, i need their bytes.
    By Florian in forum C++ Programming
    Replies: 26
    Last Post: 07-08-2008, 05:42 PM
  2. Read Bytes From File Into Integer
    By ChadJohnson in forum C Programming
    Replies: 28
    Last Post: 08-16-2004, 11:57 AM
  3. More unions and bytes
    By wildcat in forum C Programming
    Replies: 1
    Last Post: 03-05-2003, 11:52 AM
  4. unions
    By mickle in forum C Programming
    Replies: 6
    Last Post: 02-27-2003, 11:46 PM
  5. unions problems!
    By nextus in forum C++ Programming
    Replies: 3
    Last Post: 01-12-2003, 04:04 AM