gpt4 book ai didi

c - 你如何打印出一个 IEEE754 数字(没有 printf)?

转载 作者:太空狗 更新时间:2023-10-29 15:04:59 25 4
gpt4 key购买 nike

出于这个问题的目的,我有能力使用printf设施(不幸的是,我不能告诉你为什么,但现在让我们假设我知道我在做什么)。

对于 IEEE754 单精度数,您具有以下位:

SEEE EEEE EFFF FFFF FFFF FFFF FFFF FFFF

哪里S是标志,E是指数,F是分数。

对于所有情况,打印标志都相对容易,捕捉所有特殊情况,如 NaN 也是如此。 ( E == 0xff, F != 0 ), Inf ( E == 0xff, F == 0 ) 和 0 ( E == 0, F == 0 ,被认为是特殊的,因为在这种情况下不使用指数偏差)。

我有两个问题。

首先是如何最好地将非规范化数字(其中 E == 0, F != 0 )转换为规范化数字(其中 1 <= E <= 0xfe )?我怀疑这对于简化下一个问题的答案是必要的(但我可能是错的,所以请随时教育我)。

第二个问题是如何打印出规范化的数字。我希望能够以两种方式将它们打印出来,像 -3.74195E3 这样的指数方式。和非指数像 3741.95 .虽然,只是并排查看这两个,只需移动小数点就可以很容易地将前者变成后者。因此,让我们只关注指数形式。

I have a vague recollection of an algorithm I used long ago for printing out PI where you used one of the ever-reducing formulae and kept an upper and lower limit on the possibilities, outputting a digit when both limits agreed, and shifting the calculation by a factor of 10 (so when the upper and lower limits were 3.2364 and 3.1234, you could output the 3 and adjust for that in the calculation).

But it's been a long time since I did that so I don't even know if that's a suitable approach to take here. It seems so since the value of each bit is half that of the previous bit when moving through the fractional part (1/2, 1/4, 1/8 and so on).

我真的更希望不得不跋涉通过printf除非绝对必要,否则源代码,如果有人可以帮助解决这个问题,我将永远感激不已。

最佳答案

如果您想获得每次转换的准确结果,您将不得不使用任意精度的算法,就像在 printf() 实现中所做的那样。如果你想得到“接近”的结果,可能只是它们的最低有效数字不同,那么一个非常简单的基于 double 的算法就足够了:对于整数部分,重复除以十并将余数附加到形成十进制字符串(反向);对于小数部分,重复乘以十,再减去整数部分,形成小数串。

我最近写了一篇关于这个方法的文章:http://www.exploringbinary.com/quick-and-dirty-floating-point-to-decimal-conversion/ .它不打印科学记数法,但添加起来应该是微不足道的。该算法打印次正规数(我打印的结果准确,但您必须进行更彻底的测试)。

关于c - 你如何打印出一个 IEEE754 数字(没有 printf)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4274926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com