使用reinterpret_cast将未签名的char *转换为char * [英] using reinterpret_cast to convert unsigned char* to char*

查看:75
本文介绍了使用reinterpret_cast将未签名的char *转换为char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我环顾四周,但发现很难找到解决我问题的精确方法.

我要转换:

将unsigned char *转换为char *,将unsigned char *转换为const char *.

reinterpret_cast可以吗?

编译器很高兴,但是可以正确转换值吗?我认为我可以接受,除了reinterpret_cast不是可移植的.有人可以确认一下,然后告诉我不可移植性的影响是什么.

Hi,

I have looked around but have found it hard to find a precise answer to my problem.

I want to convert:

unsigned char* to char* and unsigned char* to const char*.

Is reinterpret_cast ok for this?

The compiler is happy but will the values be converted correctly? I think I gather that it is ok, except that the reinterpret_cast is not portable. Can somebody confirm this and tell me what the impact of non-portability is please. Where/what will it not port to and what will happen?

推荐答案

您想要做的事情对于这种类型的转换可能是安全的.您可以在指向相同大小的对象的指针之间进行强制转换,因此使用数组索引或指针算术不会感到惊讶.

如果您感到真正的偏执狂转换,请始终通过int将缓冲区的内容从无符号转换为有符号,但是在任何使用2补码算术的计算机上,这是过大的选择(如今大多数情况下使用). br/>
干杯,



来自以下问题的PS:

当您将指针从一种大小的数据转换为另一种大小的数据时,重新解释类型转换可能会导致问题.因此,如果将char *转换为int *,则编译器将生成不同的指令以通过这些指针进行读/写操作,因此最终结果可能不在您期望的位置.

为了获得额外的欢笑,您可以尝试使用一个指向另一个类的指针遍历一个类的对象数组,最终将破坏整个设置.诚然,您也可以使用static_cast来执行此操作,但至少可以警告您一些转换(即仅允许您在指向基类和派生类对象的指针之间进行转换).

因此,基本上要注意将A *转换为B *的任何事物,其中A和B是与继承无关的不同类.
What you want to do is probably safe for this type of conversion. You''re casting between pointers to objects of the same size so you''re not going to have any surprises using array indexing or pointer arithmetic.

If you''re feeling really paranoid convert you always convert the contents of the buffer from unsigned to signed via an int but that''s overkill on any computer with 2''s complement arithmetic (and most use that these days).

Cheers,

Ash

PS from question below:

reinterpret cast can cause problems when you convert pointers to data of one size to data of another. So if you convert char * into int * then the compiler''s going to be generating different instructions to read/write through those pointers so you can end up with things not where you expect them.

For extra hilarity you can try and iterate through an array of one class''s objects with a pointer to another class, you''ll end up damaging the whole setup. Admittedly you can do this with static_cast as well but at least that warns you about some conversions (i.e. it''ll only let you cast between pointers to base and derived class objects).

So basically look out for anything that converts A* to B* where A and B are different classes not related by inheritance.


这篇关于使用reinterpret_cast将未签名的char *转换为char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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