C++ 将无符号转换为有符号
C++ cast unsigned to signed
我尝试复制 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
[...]
即。您忘记了链接示例中的 &
。
我尝试复制 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
[...]
即。您忘记了链接示例中的 &
。