I need to build a function that returns the bit-level equivalent of (float)x without using any floating data types, operations or constants. I think I have it, but when I run the test file, it returns that there's an infinite loop. Any debugging help would be appreciated.
I'm allowed to use any integer/unsigned operations including ||, &&, if, while. Also, I can only use 30 operations
unsigned float_i2f(int x) {
printf("\n%i", x);
if (!x) {return x;}
int mask1 = (x >> 31);
int mask2 = (1 << 31);
int sign = x & mask2;
int complement = ~x + 1;
//int abs = (~mask1 & x) + (mask1 & complement);
int abs = x;
int i = 0, temp = 0;
while (!(temp & mask2)){
temp = (abs <<i);
i = i + 1;
}
int E = 32 - i;
int exp = 127 + E;
abs = abs & (-1 ^ (1 << E));
int frac;
if ((23 - E)>0)
frac = (abs << (23 - E));
else
frac = (abs >> (E - 23));
int rep = sign + (exp << 23) + frac;
return rep;
}
In response to the very helpful comments and answers, here is the updated code, now only failing for 0x80000000:
unsigned float_i2f(int x) {
int sign;
int absX;
int E = -1;
int shift;
int exp;
int frac;
// zero is the same in int and float:
if (!x) {return x;}
// sign is bit 31: that bit should just be transferred to the float:
sign = x & 0x80000000;
// if number is < 0, take two's complement:
if (sign != 0) {
absX = ~x + 1;
}
else
absX = x;
shift = absX;
while ((!!shift) && (shift != -1)) {
//std::cout << std::bitset<32>(shift) << "\n";
E++;
shift = (shift >> 1);
}
if (E == 30) { E++;}
exp = E + 127+24;
exp = (exp << 23);
frac = (absX << (23 - E)) & 0x007FFFFF;
return sign + exp + frac;
}
Anyone have any idea where the bug is in the revised code? Thank you all again!