0

I am working on a project for school that requires me to manipulate floating point numbers using only their binary representation, specifically multiplying a float by two. I am supposed to replicate the function of the following code using only bit operations (! | ^ & ~), logical operators (&&, ||), and if/while expressions.

However, I am having a problem with some of my numbers not having the correct result. For example, when I pass in 8388608 (0x800000), the output is 8388608 when it should be 16777216 (0x1000000).

Here is the code whose function we are supposed to replicate:

unsigned test_dl23(unsigned uf) {
float f = u2f(uf);
float tf = 2*f;
if (isnan(f))
  return uf;
else
  return f2u(tf);
}

And here is my attempt:

unsigned dl23(unsigned uf) {

int pullExpMask, expMask, mantMask, i, mask, signedBit
mask = 0x007fffff;

pullExpMask = (-1 << 23) ^ 0x80000000; // fills lower 23 bits with zeroes
signedBit = 0x80000000 & uf;
expMask = (uf & pullExpMask); // grabs the exponent and signed bits, mantissa bits are zeroes
mantMask = mask & uf;

if (!(uf & mask)){ // if uf has an exponent that is all ones, return uf
    return uf;
}

else if (expMask == 0){
   mantMask =  mantMask << 1;

} 
else if (expMask != 0){
  expMask = expMask + 0x00100000;
}

return (signedBit | expMask | mantMask);


}

I have been working on this problem for a long time, and any helpful tips would be greatly appreciated!

diaga
  • 11
  • 4

1 Answers1

0

I'm not sure about what numbers you are referring to as failing, but I do see a bug in your code that would cause this behavior. The section with the comment // if uf has an exponent that is all ones, return uf does not do what this describes. It will test that the mantissa part is 0 and return the unchanged number, causing the behavior you're seeing. It should probably be something like if (expMask == pullExpMask) {

Also, you need to consider the case that the exponent increment makes it all 1. It should always become an inf, and never a quiet or signaling NaN.

robot1208
  • 191
  • 1
  • 7