Compiler Error with negative global variable shift parameter

Discussion created by Didier JEANJEAN on Jul 28, 2017
Latest reply on Aug 1, 2017 by Alice_Yang

Compiler Error with negative global variable shift parameter

Default Compiler using by  KDS 3.2.0 with FreeRTOS

When shifting  like following
Int32_t x ;
Int32_t y = 8 ;
Int8_t z = -1 ;
x = y << z;
x = y >> z;

If the variables y or z are global and if z is negative the result in x becomes = 0 whatever the values it should take.
All variables to the right of the "=" must be local for the function to give a correct result with z negative.
for exemple :
x = y << (u-w);
x = y >> (u-w);
In this case it is necessary that y, u and w be declared in local variable for correct operation with (u-w) negative.



The safest solution if we don't know the declaration zone, is to achieve a macro that results in always positive shift.


#define MACRO_LEFTSHIFTSIGNED_SAMEVALUE(value,shift)     if ((shift) >= 0)    (value) <<= (shift); \
                            else             (value) >>= (-shift)


#define MACRO_LEFTSHIFTSIGNED(out,in,shift)     if ((shift) >= 0)     (out) = (in) << (shift); \
                        else             (out) = (in) >> (-shift)


#define MACRO_RIGHTSHIFTSIGNED_SAMEVALUE(value,shift)     if ((shift) >= 0)     (value) >>= (shift); \
                            else             (value) <<= (-shift)


#define MACRO_RIGHTSHIFTSIGNED(out,in,shift)     if ((shift) >= 0)     (out) = (in) >> (shift); \
                        else             (out) = (in) << (-shift)


Best regards