Reputation:
So I have this function where I extracted my fraction part of the given int so that I can output it in hex form.
Here is my code where result is the fraction part which I then print in hex form.
// getting fraction part
result = 0;
int count = 0;
for (int which_digit = 23; which_digit >0; which_digit--) {
shifted_value = f >> (23 - count);
int fractionn = (shifted_value & 1) * (1 << which_digit) ;
result += fractionn;
count++;
}
If I'm given the number 8, my program correctly prints the hex form of the fraction part. However given another number like -0.749000013, my program prints 0x3fbe76 instead of 0x3fbe77.
Does anyone know where I went wrong
Upvotes: 0
Views: 43
Reputation: 110088
Your loop end condition is which_digit > 0
, so you skip over bit #0. It should be which_digit >= 0
. You should also start with bit 22, not 23.
That said, your entire loop can be replaced by the simple result = f & 0x7fffff;
. There's no need to go bit by bit.
Upvotes: 1