当前位置:编程学习 > C/C++ >>

reinterpret_cast在编程中的应用

在某些情况下,为了适应接口类型要求,需要将int转化成uint, double转化成int64_t等,但是经过这种转化之后可能会有数据损失。
 
如果只是为了适应接口,最终还是希望读出原始数据,那么可以选用reinterpret_cast。例如:
 
[cpp] 
#include <stdio.h>  
#include <stdint.h>  
  
int main()  
{  
  int64_t i = 0;  
  double d = 1.1;  
  
  int64_t j = reinterpret_cast<int64_t&>(d);  
  double j2 = reinterpret_cast<double&>(j);  
    
  int64_t k = static_cast<int64_t>(d);  
  double k2 = static_cast<double>(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,最终结果会出错。
 
 
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,