简体   繁体   English

C ++将无符号转换为已签名

[英]C++ cast unsigned to signed

I tried to replicate this but it would not compile. 我试图复制它,但无法编译。

unsigned char x = 0;
reinterpret_cast<signed char>(x);

It says 它说

C:\Users\SXG5558\Documents\Arduino\sketch_jun30a\sketch_jun30a.ino: In function 'void setup()':

sketch_jun30a:3: error: invalid cast from type 'unsigned char' to type 'signed char'

     reinterpret_cast<signed char>(x);

                                    ^

exit status 1

EDIT: 编辑:

To be clear, I really do want to reinterpret the bits in memory from signed to unsigned. 需要明确的是,我确实希望将内存中的位从有符号重新解释为无符号。 I am writing an I2C library that reads and writes unsigned data, but I am using that library to control sensors which are signed, so I want to reinterpret cast the actual data. 我正在编写一个I2C库,该库可以读取和写入未签名的数据,但是我正在使用该库来控制已签名的传感器,因此我想重新解释转换实际数据。

The relevant part from cppreference.com is 来自cppreference.com的相关部分是

Type aliasing 类型别名

When a pointer or reference to object whose dynamic type is DynamicType is reinterpret_cast (or C-style cast) to a pointer or reference to object of a different type AliasedType, the cast always succeeds, but the resulting pointer or reference may only be used to access the object if one of the following is true: 当将动态类型为DynamicType的对象的指针或引用重新解释为其他类型的AliasedType的对象的指针或引用的reinterpret_cast(或C样式强制转换)时,强制转换始终成功,但是结果指针或引用只能用于如果满足以下条件之一,则访问该对象:

[...] [...]

  • AliasedType is the (possibly cv-qualified) signed or unsigned variant of DynamicType AliasedType是DynamicType的(可能是cv限定的)有符号或无符号变体

[...] [...]

ie. 即。 you forgot the & from the example you linked. 您从链接的示例中忘记了&

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM