从长位双 [英] Double from long bits

查看:121
本文介绍了从长位双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 unsigned long long (或 uint64_t )值,并想将其转换为 double 。 double将具有与 long 值相同的位模式。这种方式我可以设置双手动的位。

I have an unsigned long long (or uint64_t) value and want to convert it to a double. The double shall have the same bit pattern as the long value. This way I can set the bits of the double "by hand".

unsigned long long bits = 1ULL;
double result = /* some magic here */ bits;

我正在寻找一种方法。

推荐答案

这样做的便携式方法是使用 memcpy (您也可以有条件地使用 reinterpret_cast 或联合,但是这些不能确定是可移植的,因为它们违反严格别名规则的字母):

The portable way to do this is with memcpy (you may also be able to conditionally do it with reinterpret_cast or a union, but those aren't certain to be portable because they violate the letter of the strict-alias rules):

// First, static assert that the sizes are the same
memcpy(&result, &bits, sizeof(bits));

但在你确定你知道你在做什么和什么浮点表示使用(虽然IEEE754是一个流行/常见的选择)。你需要避免所有类型的问题值,例如无穷大,NaN和非正规数字。

But before you do make sure you know exactly what you're doing and what floating point representation is being used (although IEEE754 is a popular/common choice). You'll want to avoid all kinds of problem values like infinity, NaN, and denormal numbers.

这篇关于从长位双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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