C++ 将无符号转换为有符号

标签 c++ arduino reinterpret-cast

我试图复制 this但它不会编译。

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

它说

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

编辑:

明确地说,我真的很想将内存中的位从有符号重新解释为无符号。我正在编写一个读取和写入未签名数据的 I2C 库,但我正在使用该库来控制已签名的传感器,因此我想重新解释转换实际数据。

最佳答案

相关部分来自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:

[...]

  • AliasedType is the (possibly cv-qualified) signed or unsigned variant of DynamicType

[...]

即。您忘记了链接示例中的 &

关于C++ 将无符号转换为有符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38133462/

相关文章:

c++ - 在 Type 和 Wrapper<Type> 之间 reinterpret_cast 是否安全?

c++ - 违反严格别名规则的类型转换

C++ 结构初始化

c++ - 使用构造函数初始化列表初始化结构时出现问题

c++ - Cppcheck无法识别命令

c++ - 编译时在文件中包含字符串

arduino - Arduino 上的中断速度太快

C++ union 与 reinterpret_cast

取决于输入的 C++ 矩阵大小无法编译

c++ - 代码中未初始化的指针