mgspan
mgspan

Reputation: 21

Initializing a member of an integer array with a floating point literal in C++

I have an array of 32-bit long integers. Some of the elements will afterwards be used as 32-bit floats. I would like to supply an initializer list to initialize these floating point values correctly. For example, if the first two elements are used as integers, and the third as float, and I wish to initialize the third element to be equal to 100.0, I am forced to do this:

long a[3]={10,20,0x42c80000};

This works fine, but is not very expressive.

If I do this:

long a[3]={10,20,100.0};

The compiler will convert the floating point literal to 0x64.

I do not have a C++11 compiler, so using a union will not work.

Any ideas?

Upvotes: 1

Views: 852

Answers (3)

Hayt
Hayt

Reputation: 5370

What you are doing when you assign it to the long array it will do an implicit conversion. If you want to store the byte-value inside the variable you can use memcpy

So what you can do (and note this is pretty dangerous in case your type-sizes are not the same) have a function like this

long toLongRepresantation(float f)
{
   long ret;
   memcpy(&ret,&f,sizeof(long));
   return ret;
}

You can also template this but you should make sure that the size for both types are the same.

Upvotes: 1

Raindrop7
Raindrop7

Reputation: 3911

why you don't use struct or class instead?

struck a
{
    int    iValue1; 
    float  fValue1;
    double dValue1;
    char   cValue1;

    int    iValue2[10]; // array of ints
    float  fValue2[5 ]; // array of floats
    // ...
};

Upvotes: 0

paul-g
paul-g

Reputation: 3877

Unions don't require C++11 so go ahead and use them. However, it's generally a bad idea to mix objects/elements of different types in a single data structure, if they don't belong together semantically.

It will make your code for manipulating said data structure brittle and error-prone. I'd suggest rethinking your semantics and seeing why you need both longs and floats in the same array. They could be stored in separate data structures. Also floats can store all longs accurately (though with different bitwise representation), so why not just create a float array to begin with?

Upvotes: 8

Related Questions