How to convert double to unsigned long long under rounding mode != FE_TOWARDZERO?
Extra: why there is no ullrint function?
How to convert double to unsigned long long under rounding mode != FE_TOWARDZERO?
Extra: why there is no ullrint function?
Copyright © 2021 Jogjafile Inc.
The standard C99 math functions
trunc(),ceil(),floor(), andrint()(with an appropriately set rounding mode) can be used to first round thedoublevalue to the next integer value using the desired rounding mode, before converting tounsigned long longwith a cast. Note that sufficiently largedoublevalues (those with magnitude >= 253) are guaranteed to be integers, so there are no double-rounding issues in this approach.Alternatively (e.g. when using a tool chain that only supports an older ISO-C standard that does not offer these standard math functions), one can easily perform the conversion with a little straightforward bit manipulation. The following example code demonstrates both approaches. It assumes that
uint64_tandunsigned long longare identical under the hood, and thatdoublemaps to IEEE-754binary64.