安全地将长整数加倍到uint64_t [英] Safe to cast long double to uint64_t

查看:55
本文介绍了安全地将长整数加倍到uint64_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 std :: hash< std :: string>()为C ++中的字符串创建哈希码。该函数返回一个 long double ,但是出于继承的原因,我需要一个 uint64_t

I'm using std::hash<std::string>() to create a hash code for a string in C++. The function returns a long double but I need a uint64_t for inherited reasons.

这样的演员安全吗?

推荐答案

C ++标准段落3.9 .1.8说:

C++ Standard paragraph 3.9.1.8 says:


有三种浮点类型:float,double和long double。 double类型至少提供与float一样的精度,long long类型提供至少与double一样高的精度。 float类型的值集是double类型的值集的子集; double类型的值集是long double类型的值集的子集。浮点类型的值表示形式是实现定义的。整数和浮点类型统称为算术类型。标准模板std :: numeric_limits(18.3)的专业化应指定实现的每种算术类型的最大值和最小值。

There are three floating point types: float, double, and long double. The type double provides at least as much precision as float, and the type long double provides at least as much precision as double. The set of values of the type float is a subset of the set of values of the type double; the set of values of the type double is a subset of the set of values of the type long double. The value representation of floating-point types is implementation-defined. Integral and floating types are collectively called arithmetic types. Specializations of the standard template std::numeric_limits (18.3) shall specify the maximum and minimum values of each arithmetic type for an implementation.

几乎只说长双精度类型应该比浮点类型长。

Which pretty much only says that the long double type should be... longer than the float type.

实际上,长双精度通常是80到128位宽,如此处所述: http://en.cppreference.com/w/cpp/language/类型

这会强制将uint64_t强制转换为uint64_t,因为长双精度中的某些位可能不合适。

In practice, long double are usually 80- to 128-bit wide, as explained here: http://en.cppreference.com/w/cpp/language/types
This makes casting (I assume reinterpret_cast) to a uint64_t unsafe, as the some bits from the long double will probably not fit.

这篇关于安全地将长整数加倍到uint64_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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