[Cfp-interest] FUNCTIONS - FP to int conversion

Fred J. Tydeman tydeman at tybor.com
Thu Jun 3 14:27:21 PDT 2010


Here are two other ways to convert from FP to integer.

1. A pair of functions for each FP type.

unsigned long long int ufrom_FP( FP x, int round, int inexact, int bits );
  signed long long int  from_FP( FP x, int round, int inexact, int bits );

'round' indicates the rounding direction (FE_* rounding macro)

'inexact' indicates if inexact should be raised if FP is not an
integer (0 => ignore inexact, 1 => raise inexact if appropriate)

'bits' is the number of bits in the final integer type being convert
to (needed to see if number exceeds the range of the final type, and
hence, raise invalid).  For normal integer types, it would be:
  CHAR_BIT * sizeof(type)

Since C has integer bit-fields, there needs to be a way to convert
from a FP number to any sized integer bit-field and be able to detect
if the FP number is too large (so as to raise invalid).

A typical call would be: 
 unsigned short i = ufrom_ld( 1.7L, FE_UPWARD, 1, 16 );
which would result in 'i' being 2, and inexact being raised.

Another call could be:
 struct {
    signed int a:5 =  from_f( 127.5f, FE_NEAREST, 0, 5 );
  unsigned int b:5 = ufrom_f( 127.5f, FE_NEAREST, 0, 5 );
 }
which would result in 'a' having an unspecified value and 'invalid'
being raised (since 128 does not fit in a 5-bit integer).  While 'b'
would have the value 0u (128 mod 32) and neither inexact nor invalid
would be raised.

2. Use existing functions.

Use one of ceil, floor, trunc, round, roundeven, to convert an FP
value to an integer FP value.

Compare result of above to original argument to detect inexact
(if needed).

Assign via '=' or a cast to an integer object.  That is supposed to
raise invalid if it is out of range (but most compilers fail to do
this in all cases).

---
Fred J. Tydeman        Tydeman Consulting
tydeman at tybor.com      Testing, numerics, programming
+1 (775) 358-9748      Vice-chair of PL22.11 (ANSI "C")
Sample C99+FPCE tests: http://www.tybor.com
Savers sleep well, investors eat well, spenders work forever.



More information about the Cfp-interest mailing list