Compiler Error with negative global variable shift parameter

キャンセル
次の結果を表示 
表示  限定  | 次の代わりに検索 
もしかして: 

Compiler Error with negative global variable shift parameter

864件の閲覧回数
didierjeanjean
Contributor III

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;
or
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);
or
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.

Workaround:

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

0 件の賞賛
返信
1 返信

717件の閲覧回数
Alice_Yang
NXP TechSupport
NXP TechSupport

Hello didier,

Thanks a lot for your sharing.

BR

Alice

0 件の賞賛
返信