0

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;

Mappan
  • 2,537
  • 2
  • 22
  • 27
  • 1
    Check out http://en.wikipedia.org/wiki/Single-precision_floating-point_format - you need to flip the top bit of the input and return the result, unless the input is a NaN – moonshadow Sep 26 '12 at 09:15
  • If that comment was written by your teacher it sure is confusing. – CrazyCasta Sep 26 '12 at 09:34
  • 4
    It's worth noting that the "negation" this assignment defines is contrary to the IEEE-754 standard, which specifies that negation should flip the sign bit of the encoding for all inputs, including NaNs (§5.5.1 in 754-2008). – Stephen Canon Sep 26 '12 at 11:40

1 Answers1

5

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.

Skizz
  • 69,698
  • 10
  • 71
  • 108