I am trying to return the result of casting a single precision float to an int just from its bit string. I correctly grab the sign bit, exponent and mantissa from the bit string but I am unsure how to ensure a float is in the range (0x80000000<float<0x7fffffff) solely from its bit string.
Additionally, I am confused when I should round the result to 0? It appears that casting to an int does round to 0, I just don't know when or why this occurs?
Here is my code so far:
int convertFloatToAnInt(unsigned f) {
//trying to return (inf)f
int signBit = (f >> 31) & 1;
int exponent = (f >> 23) & 0xFF;
int mantissa = f & 0x7FFFFF;
exponent = exponent - 127;
int truncatedFloat = 0;
//trucate based on the exponent with decimal at 23rd bit
truncatedFloat = (mantissa>>(23-exponent));
//add the implicit 1 back to the mantissa
truncatedFloat |= (1<<exponent);
//change the sign if needed
if (signBit) {
truncatedFloat = ~(truncatedFloat)+1;
}
return truncatedFloat;//(int)f
}
I will assume the IEEE 754 single-precision representation of
floatand 32-bit width forintandunsignedas indicated in the question.The
inthas range [-2^31; 2^31-1].The significand in the
floatis essentially a 24 bit value multiplied by 2^-23 (i.e. shifted 23 places to the right). This will fit within 31 bits if it is shifted at most 30 places to the left. Hence, if the exponent is at most 30, then the value will fit into anint. However, there is one case where the exponent is 31 which also fits: if the value is -2^31, i.e. the sign bit is set and the exponent is 31 and the mantissa is 0.When doing the conversion, these checks must be made before doing the bit-shifting to avoid undefined behaviour. Also, it must be checked if the mantissa should be shifted left or right since shifting a negative amount is undefined behaviour.
Thus an implementation could be:
Note: calling this function requires passing the bit pattern of a float as an unsigned. This can be done as follows:
It is important to notice that
(int)xwill be undefined behaviour ifxdoes not fit in anint. The functiontoInt()will not have undefined behaviour for any value ofx. However, of course,toInt()relies heavily on implementation-defined behavior such as the representation offloat.