Hi,
I'm trying to solve a riddle in a programming test.
Disclaimer: It's a test for a job, but I'm not looking for an answer. I'm just looking for an understanding of how to do this. The test requires that I come up with a set of solutions to a set of problems within 2 weeks, and it doesn't state a requirement that I arrive at the solutions in isolation.
So, the problem:
I have a 32-bit number with the bits arranged like this:
siiiiiii iiiiiiii ifffffff ffffffff
Where:
- s is the sign bit (1 == negative)
- i is 16 integer bits
- f is 15 fraction bits
The assignment is to write something that decodes a 32-bit integer into a floating-point number. Given the following inputs, it should produce the following outputs:
input output
0x00008000 1.0
0x80008000 -1.0
0x00010000 2.0
0x80014000 -2.5
0x000191eb 3.14
0x00327eb8 100.99
I'm having no trouble getting the sign bit or the integer part of the number. I get the sign bit like this:
boolean signed = ((value & (1 << 31)) != 0);
I get the integer and fraction parts like this:
int wholePart = ((value & 0x0FFFFFFF) >> 15);
int fractionPart = ((value & 0x0000FFFF >> 1));
The part I'm having an issue with is getting the number in the last 15 bits to match the expected values. Instead of 3.14, I get 3.4587, etc.
If someone could give me a hint about what I'm doing wrong, I'd appreciate it. More than anything else, the fact that I haven't figured this out after hours of messing with it is kind of driving me nuts. :-)