Search code examples
c++arduinoreinterpret-cast

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.


Solution

  • The relevant part from cppreference.com is

    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

    [...]

    ie. you forgot the & from the example you linked.