This is a homework question and I'm completely out of ideas (C programming).
Instructions:
/*
* float_neg - Return bit-level equivalent of expression -f for
* floating point argument f.
* Both the argument and result are passed as unsigned int's, but
* they are to be interpreted as the bit-level representations of
* single-precision floating point values.
* When argument is NaN, return argument.
* Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
* Max ops: 10
* Rating: 2
*/
unsigned float_neg(unsigned uf) {
return 2;
I've tried simply going return -uf; and other things but I just have no idea what to do.
Help?
The following conditions may be assumed:
- Uses 2s complement, 32-bit representations of integers.
- Performs right shifts arithmetically.
- Has unpredictable behavior when shifting an integer by more than the word size.
-EDIT
Solved it: return uf^0x80000000;
Ignoring for now the absurdity of the question, the question is asking about the floating point format, presumably, the IEEE-754 standard that the Intel chips use. The binary format of the IEEE number for 32bits is:-
So, negating the value is trivial. Before toggling the top bit, you must check for various specific values: Nan, Inf, etc; and these are detailed in the IEEE specification.
Note that you can have +0 and -0.
Simply returning the integer negation won't work as that preforms a 2's complement negation, so integer value 1 becomes 0xffffffff which, when interpreted by the FPU would be a massively different value.