Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need some help making these instructions a little clearer in c++; I don\'t und

ID: 3662283 • Letter: I

Question

I need some help making these instructions a little clearer in c++; I don't understand what it means.

"In order to do the appropriate bitwise operations on the float it must first be cast to an int but (int) f (assuming f is the variable you have stored you float in) will not work as the cast will convert the float representation to the 2's compliment integer representation. The fix is to take the address of the float, cast it as an unsigned int*, and then dereference."

The first part I can understand, but I don't know what the instructions mean in the bolded part.

Also, how do you read a float with bitwise operands?

Explanation / Answer

t the language level, there's no such thing as "bitwise operation on floating-point numbers". Bitwise operations in C/C++ work on value-representation of a number. And the value-representation of floating point numbers is not defined in C/C++. Floating point numbers don't have bits at the level of value-representation, which is why you can't apply bitwise operations to them.

All you can do is analyze the bit content of the raw memory occupied by the floating-point number. For that you need to either use a union as suggested below or (equivalently, and only in C++) reinterpret the floating-point object as an array of unsigned char objects, as in

float f = 5;
unsigned char *c = reinterpret_cast<unsigned char *>(&f);
// inspect memory from c[0] to c[sizeof f - 1]

And please, don't try to reinterpret a float object as an int object, as other answers suggest. That doesn't make much sense, that is illegal, and that is not guaranteed to work in compilers that follow strict-aliasing rules in optimization. The only legal way to inspect memory content in C++ is by reinterpreting it as an array of [signed/unsigned] char.

Also note that you technically aren't guaranteed that floating-point representation on your system is IEEE754 (although in practice it is unless you explicitly allow it not to be, and then only with respect to -0.0, ±infinity and NaN)