Reputation: 2327
I am trying to typecast a float
to unsigned char
using the following C++ code:
#include <iostream>
int main()
{
std::cout << int((unsigned char)((float)-10)) << "\n";
std::cout << int((unsigned char)((float)300)) << "\n";
return 0;
}
gcc 12.1 output:
0
255
which can be tried here. It nicely clamps the values to 0
and 255
, and this is what I expect to get in any operating system. However, the problem occurs when I try the same code in Visual Studio 2022, which can be tried here.
Visual Studio output
246
44
It looks to me that 246
is actually 256-10
and the second output 44
is 300-256
. May I know why Visual Studio is producing a different result?
How can I make this simple casting cross-platform?
Upvotes: 0
Views: 137
Reputation: 119877
Floating-integral conversions [conv.fpint]
Upvotes: 10