Safe to cast long double to uint64_t

大憨熊 提交于 2019-12-12 10:24:59

问题


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.

Is such a cast safe?


回答1:


C++ Standard paragraph 3.9.1.8 says:

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.

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.




回答2:


The std::hash call operator returns a value of type size_t that represents the hash value of the parameter.

Thus, the assumption of the question, about long double return type, seems to be incorrect.



来源:https://stackoverflow.com/questions/21706877/safe-to-cast-long-double-to-uint64-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!