// mask_1 should be 0x0000FFFF, but sum won't be greater than 16 unsigned mask_1 = 0xFF; unsigned a_1 = sum & mask_1; unsigned b_1 = (sum & ~mask_1) >> 16; sum = a_1 + b_1;
//float /* * floatScale2 - Return bit-level equivalent of expression 2*f for * floating point argument f. * Both the argument and result are passed as unsigned int's, but * they are to be interpreted as the bit-level representation of * single-precision floating point values. * When argument is NaN, return argument * Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while * Max ops: 30 * Rating: 4 */ unsignedfloatScale2(unsigned uf){ unsigned s = (uf >> 31) & 1; // 取出符号 unsigned e = (uf >> 23) & 0xFF; // 取出阶码 unsigned m = (uf << 9) >> 9; // 取出小数 if (e == 0xFF) // NaN or 无穷大 return uf; if (e == 0) { // 非规格化数 m <<= 1; // 非规格化数平滑过渡 } else { e += 1; } return (((s << 8) + e) << 23) + m; }
/* * floatFloat2Int - Return bit-level equivalent of expression (int) f * for floating point argument f. * Argument is passed as unsigned int, but * it is to be interpreted as the bit-level representation of a * single-precision floating point value. * Anything out of range (including NaN and infinity) should return * 0x80000000u. * Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while * Max ops: 30 * Rating: 4 */ intfloatFloat2Int(unsigned uf){ unsigned s = (uf >> 31) & 1; // 取出符号 unsigned e = (uf >> 23) & 0xFF; // 取出阶码 unsigned m = (1 << 23) + ((uf << 9) >> 9); // 取出小数
if (e == 0xFF) { return1 << 31; } if (e >= 127) { if (e <= 127+23) { m >>= (23-e+127); } else { if (e-127-23 >= 8) { //溢出 return1 << 31; } m <<= e-150; } if (s == 1) return ~m + 1; elsereturn m; } else { return0; } }
floatPower2
由于 IEEE 设计浮点数的特点就是基于x*2^y。所以这题非常简单。 另外别忘了按照题目要求处理 too small 和 too large。
/* * floatPower2 - Return bit-level equivalent of the expression 2.0^x * (2.0 raised to the power x) for any 32-bit integer x. * * The unsigned value that is returned should have the identical bit * representation as the single-precision floating-point number 2.0^x. * If the result is too small to be represented as a denorm, return * 0. If too large, return +INF. * * Legal ops: Any integer/unsigned operations incl. ||, &&. Also if, while * Max ops: 30 * Rating: 4 */ unsignedfloatPower2(int x){ if (x > 127){ // too large return (0xFF << 23); } elseif (x < -126) { // too small return0; } else { return ((127+x) << 23); } }%