This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

bit-shift operation in the compiler with CCS studio 3.3



We have encountered a problem with a bit-shift operation in the compiler with CCS studio 3.3. Let's consider the following example:

 

ulong sampleHolder;

 

 

for ( j = 0 ; j < 3; j++ ) 

{

   sampleHolder += (SampleData[j].data[index] << (j * 10) ); // 311 format

}

 

Here I try to bit shift the data in "SampleData" and store it in sampleHolder variable. I need to shift the data 0, 10 and 20 bits to the left. This works for bitshifting of 0 and 10 bits to the left but for 20 it fails (it returns 0).

 

After that I created a simple example:

 

ulong sampleHolder;

 

sampleHolder = 1 << 0;

sampleHolder = 1 << 10;

sampleHolder = 1 << 20;

 

This also works for the first and second time (0 and 10) but for 20 it fails. This should work properly because ulong is a 32 bit variable.

 

But then if I use multiplication instead of bit-shifting it works perfectly:

 

            sampleHolder = 0;

                       

            multiplier = 1;

            for ( j = 0 ; j < 3 ; j++ ) 

            {

                        // Write 3 10 bit samples into a 4 byte variable

                        tempLong = SampleData[j].data[index] * multiplier;

                        sampleHolder += (tempLong); // 311 format

                        multiplier *= 1 << 10;

            }

 

 

Could you please analyse the included examples and tell us if we are doing something wrong or is it a compiler error?

 

 

  • sampleHolder is a ulong, but the constant '1' is an int.  Likely 16 bits on your platform.   Left shifting a 16 bit value by 20 bits is undefined.   You need to cast the constant to the appropriate width.

    -Lori

  • Lori is correct, but I'll give an answer that is a bit more general.  In the book The C Programming Language (2nd Ed) in section A7.8, it says of shift operations:

    The result is undefined if the right operand is negative, or greater than or equal to the number of bits in the left expression's type.

    Thus, it is the user's job to make sure the type of the left expression is big enough for all possible values of the right expression.  The most common technique is casting:

    (long) left_expr << right_expr

    If the left expression is a constant, you can get the same effect with a suffix:

    1L << right_expr

    Thanks and regards,

    -George

     

  • Thanks for the great feedback.  That resolved the issue.