如果只是为了适应接口,最终还是希望读出原始数据,那么可以选用reinterpret_cast。例如:
[cpp]
#include
#include
int main()
{
int64_t i = 0;
double d = 1.1;
int64_t j = reinterpret_cast(d);
double j2 = reinterpret_cast(j);
int64_t k = static_cast(d);
double k2 = static_cast(k);
printf("org=%lf, reintterpret forw(double=>int64_t)=%ld\t, reintterpret back(int64_t=>
double)=%lf\n", d, j, j2);
printf("org=%lf, static forw(double=>int64_t)=%ld\t, static back(int64_t=>double)=%lf\n", d, k, k2);
}
编译后的输出结果:
[sql]
[xiaochu.yh@tfs035040 cpp]$ ./a.out
org=1.100000, reintterpret forw(double=>int64_t)=4607632778762754458 , reintterpret back(int64_t=>double)=1.100000
org=1.100000, static forw(double=>int64_t)=1 , static back(int64_t=>double)=1.000000
可以看到,使用了static_cast之后精度数据被丢失了。而reinterpret_cast是一种二进制转化,并不关心数据的语义。
使用reinterpret的时候需要注意的是存储空间需要足够,如果将double转成int32_t,最终结果会出错。