Aug 27, 2016 at 3:48pm UTC
Hi, I just compiled a program containing following function:
1 2 3 4 5
inline float * align16bytes(float * f)
{ unsigned int i = reinterpret_cast <unsigned int >(f);
i = (i + 15) & ~15;
return reinterpret_cast <float *>(i);
};
And there is the following error in the 2nd line
[Error] cast from 'float*' to 'unsigned int' loses precision [-fpermissive]
Do you have an idea how to fix it?
Last edited on Aug 27, 2016 at 3:49pm UTC
Aug 27, 2016 at 3:58pm UTC
Change unsigned int to uintptr_t.
Without any other context, this throws some serious red flags.
Aug 27, 2016 at 4:08pm UTC
It didn't help - still the same error
Edit:
It helped after changing the second "unsigned int". Thx :)
I don't know what a phrase "to throw a red flag" means. Can u explain?
Last edited on Aug 27, 2016 at 4:17pm UTC
Aug 27, 2016 at 4:33pm UTC
Why cast a float to an integer?
You'll risk losing some of the true value of the float unless its value is small enough to fit inside that integer.
A 4-byte float can hold about 3.403E +/- 38, a 4-byte integer can hold –2,147,483,648 to 2,147,483,647 far less than the range of values a float can represent.
Aug 27, 2016 at 4:39pm UTC
I didn't write this code. I used a ready code and now I'm trying to compile it
Aug 27, 2016 at 4:56pm UTC
It isn't a cast from
float to int. Rather it is a cast from
pointer to int.
I'm sure there are more correct ways to do this, but possibly...
1 2 3 4 5 6
inline float * align16bytes(float * f)
{
unsigned long long i = reinterpret_cast <unsigned long long >(f);
i = (i + 15) & ~15ULL;
return reinterpret_cast <float *>(i);
}
Note, a pointer and an integer need not be the same length. For example in a 64-bit environment a pointer may be 64-bits but an integer just 32-bits.
Last edited on Aug 27, 2016 at 5:13pm UTC
Aug 27, 2016 at 10:15pm UTC
~(uintptr_t)15 would be preferable to the suffix.