从浮点转换为自定义数字类型 [英] convert from float-point to custom numeric type

查看:115
本文介绍了从浮点转换为自定义数字类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了自己的固定类型的整数类型,并且该库在很多编译器和平台上都能正常工作,唯一要解决的问题是将内置的浮点类型转换为我的类型。



浮点类型可能有小尾数,但随着指数可能有很大的价值,所以如果我选择铸浮动 double long double 说出 long long unsigned long long 可能会发生截断。

如果编译器使用IEEE-754规范,则很容易提取尾数和指数,但如果编译器使用其他格式呢。



所以,我的问题是否有任何通用算法,允许我从浮点数点使用只有语言功能?



感谢

解决方案

可能会找到有用的我的答案有点类似的任务离子在这里。这个想法是,如果底层格式是二进制的,那么如果尾数中没有比最大整数类型中的位更多的数据,那么保证能够毫无损失地提取尾数和指数。您可以使用 double frexp(double value,int * exp); double ldexp(double x,int exp); 为此目的。

另一个选项是使用的数字 sprintf() %a 来获取所有的数字,然后手动将文本表达转换为您所需要的。


I've created my own fixed-type integer types and the library works fine with many compilers and platforms, the only problem left to solve is to convert from built-in float-point types to my types.

The float-point types may have small mantissa but along with exponent it may have big value so if i choose to cast float, double, or long double say to long long or unsigned long long a truncation may occur.

If the compiler use IEEE-754 specification it'll be easy to extract mantissa and exponent, but what if the compiler use some other format.

So, my question: is there any generic algorithm that allows me to extract the full value from a float-point using only the language features?

thanks

解决方案

You may find useful my answer to a somewhat similar question here. The idea is that if the underlying format is binary, you are pretty much guaranteed to be able to extract the mantissa and exponent without loss if there are no more bits in the mantissa than there are in the biggest integer type. You can use double frexp(double value, int *exp); and double ldexp(double x, int exp); for the purpose.

Another option would be to sprintf() the number using %a to get all the digits and then manually convert the textual representation into what you need.

这篇关于从浮点转换为自定义数字类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆