CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2005
    Posts
    11

    Unhappy using unions with float and long

    i need to know how to use unions to extract and return the sign, the intended exponent value and the full 24-bit mantissa from a 32-bit floating-point number. I know that it has something to do with using the fact that the two share the same space because of the union, but i'm not too sure on the coding to make the values apparant...

  2. #2
    Join Date
    May 2000
    Location
    Scotland, Livingston.
    Posts
    728

    Re: using unions with float and long

    Code:
    typedef union {
        float FloatVal;
        struct {
            unsigned int SignBit:1;        // 1 bit for the sign
            unsigned int Exponent:7;    // 7 bits for the exponent
            unsigned int Mantissa:24;   // 24 bits for the mantissa
        } FloatBits;
    } FLOAT;
    
    FLOAT f;
    f.FloatVal = 1.234f;
    Basically all the elements in a union occupy the same space in memory. A union simply defines a set of templates (names and types) for accessing that memory.

    So. The above allows you to declare a variable of type FLOAT and access its memory (4 bytes) as a float (f.FloatVal) or as a set of bit fields representing the individual parts that make up the float representation f.FloatBits.Exponent etc.

    (ps. I have not compiled the above, but it should be enough to point you in the right direction if it dosent work)
    Dave Mclelland.

  3. #3
    Join Date
    Aug 2005
    Posts
    11

    Re: using unions with float and long

    thanks heaps, thats what i was looking for, well it was enough to point me in the right direction. thanks again.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured