How to manually (bitwise) perform (float)x?

后端 未结 3 423
一生所求
一生所求 2020-12-01 22:15

Now, here is the function header of the function I\'m supposed to implement:

/*
 * float_from_int - Return bit-level equivalent of expression (float) x
 *            


        
3条回答
  •  情深已故
    2020-12-01 22:27

    The problem is that the lowest int is -2147483648, but the highest is 2147483647, so there is no absolute value of -2147483648. While you could work around it, I would just make a special case for that one bit pattern (like you do for 0):

    if (x == 0)
        return 0;
    if (x == -2147483648)
        return 0xcf000000;
    

    The other problem is that you copied an algorithm that only works for numbers from 0 to 32767. Further down in the article they explain how to expand it to all ints, but it uses operations that you're likely not allowed to use.

    I would recommend writing it from scratch based on the algorithm mentioned in your edit. Here's a version in C# that rounds towards 0:

    uint float_from_int(int x)
    {
        if (x == 0)
            return 0; // 0 is a special case because it has no 1 bits
    
        // Save the sign bit of the input and take the absolute value of the input.
        uint signBit = 0;
        uint absX = (uint)x;
        if (x < 0)
        {
            signBit = 0x80000000u;
            absX = (uint)-x;
        }
    
        // Shift the input left until the high order bit is set to form the mantissa.
        // Form the floating exponent by subtracting the number of shifts from 158.
        uint exponent = 158;
        while ((absX & 0x80000000) == 0)
        {
            exponent--;
            absX <<= 1;
        }
    
        // compute mantissa
        uint mantissa = absX >> 8;
    
        // Assemble the float from the sign, mantissa, and exponent.
        return signBit | (exponent << 23) | (mantissa & 0x7fffff);
    }
    

提交回复
热议问题