Error with casting from float to int

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
Change unsigned int to uintptr_t.

Without any other context, this throws some serious red flags.
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
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.
I didn't write this code. I used a ready code and now I'm trying to compile it
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
~(uintptr_t)15 would be preferable to the suffix.
Topic archived. No new replies allowed.