Return bit-level equivalent of expression -f for floating point argument f

Mappan picture Mappan · Sep 26, 2012 · Viewed 7.2k times · Source

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:

  1. Uses 2s complement, 32-bit representations of integers.
  2. Performs right shifts arithmetically.
  3. Has unpredictable behavior when shifting an integer by more than the word size.

-EDIT

Solved it: return uf^0x80000000;

Answer

Skizz picture Skizz · Sep 26, 2012

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:-

enter image description here

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.