Rounding to the nearest floating point integer

How can I round a floating point number to the nearest integer? I am looking for an algorithm in terms of binary since I have to implement the code in the assembly.

+5
source share
3 answers

UPDATED method for correct rounding to even.

The main algorithm:

Store 23-exponent + 1st bit (after decimal point). Then zero out the (23-exponential) least significant bits. Then use the saved bit and the new LSB for rounding. If the saved bit is 1, add it to the LSB of the non-truncated part and normalize if necessary. If the saved bit is 0, do nothing.

**

To compare the results with the IEEE-754 standard:

** , (23-), (22-). . (23- + 1) ( ) . (23-) ).

, .

1, 0, LSB, LSB 1.

1, 1, LSB.


:

x = 62,3

    sign exponent             mantissa
x =  0      5       (1).11110010011001100110011

1: + 1- ( )

+ 1 = 6-

savedbit = 0

2: 23- 23- = 18, 18 LSB

    sign exponent             mantissa
x =  0      5       (1).11110000000000000000000

3: 0, , 62.


:

x = 21.9

    sign exponent             mantissa
x =  0      4       (1).01011110011001100110011

1: + 1- ( )

+ 1 = 5-

savedbit = 1

2: 23- 23- = 19, 19 LSB

    sign exponent             mantissa
x =  0      4       (1).01010000000000000000000

3: 1, LSB 22, :

:

    sign exponent             mantissa
x =  0      4       (1).01010000000000000000000

:

+                          1

22:

    sign exponent             mantissa
x =  0      4       (1).01100000000000000000000
+5

SSE : http://www.musicdsp.org/showone.php?id=246

inline int float2int(float x) {
    int i;
    __asm {
        fld x
        fistp i
    }
    return i;
}
0

1, 1, 1, . 0.5 . .

-2
source

All Articles