I notice under GCC and Clang, when I cast a float
value to int
, something is done on the backend to convert the true floating point data into an integer -- the fractional portion is ignored, and the whole number portion is the part which gets interpreted as int
. For example, the expression ( unsigned int ) 101.75f
evaluates to 101
.
This is neat, but I am curious: is this just some behavior these particular compilers have built in, or is it actually a required feature of the C programming language?
If the former case is true, is there any way to disable this functionality? I would be interested if there is a super simple way to naively cast a float
value to unsigned int
without doing any "actual" conversion. For example, I used this webpage to obtain the IEEE-754 representation of 101.75f
, which is 01000010110010111000000000000000
. If I were to naively interpret these 32 bits as an unsigned int
value myself, my original expression ( unsigned int ) 101.75f
would evaluate to (depending on endianness) 1120632832
instead of 101
.
Converting a floating point type to an integer type does truncate the fractional part. This is dictated by section 6.3.1.4p1 of the C standard:
When a finite value of real floating type is converted to an integer type other than
_Bool
, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.
This is because both an explicit conversion (i.e. a cast) and an implicit conversion convert the value of an expression from one type to another. What it seems like you're asking about is whether the representation of a float
can be reinterpreted as an int
.
You can use a union
to perform such a reinterpretation:
union {
unsigned int i;
float f;
} u;
u.f = 101.75f;
printf("%u\n", u.i);