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:
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
floatcan be reinterpreted as anint.You can use a
unionto perform such a reinterpretation: