I need to create a function that returns the equivalent of the bit level (float) x without using any floating data types, operations or constants. I think I have this, but when I run the test file, it returns that there is an infinite loop. Any debugging help would be appreciated.
I am allowed to use any integer / unsigned operations, including ||, & &, if, while. In addition, 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 very useful comments and answers, here is the updated code, now only a glitch 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 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; }
Does anyone know where the error is in the revised code? Thanks again!
c type-conversion binary bit unsigned-integer
singmotor
source share