Main Content

Generate Code Containing Right Shifts on Signed Integers

This example shows how to control whether the generated code contains right shifts on signed integers. Generated code that does not contain right shifts on signed integers first casts the signed integers to unsigned integers, and then right shifts the unsigned integers.

Some coding standards, such as MISRA, do not allow right shifts on signed integers because different hardware can store negative integers differently. For negative integers, you can get different answers depending on the hardware. If you want to increase your chances of producing MISRA C compliant code, do not allow right shifts on signed integers.

Example Model

To generate code with right shifts on signed integers, create this model. A signal of Data type int16 feeds into a Shift Arithmetic block. In the Shift Arithmetic Block Parameters dialog box, the Bits to shift > Direction parameter is set to Right. The Bits to shift > Number parameter is set to 3.

Generate Code Containing Right Shifts on Signed Integers

  1. Open the Model Configuration Parameters dialog box and select the Code Style tab. The Allow right shifts on signed integers parameter is on by default.

  2. Generate code for the model.

In the rightshift.c file, the rightshift_step function contains this code:

rightshift_Y.Out1 = (int16_T)(rightshift_U.In1 >> 3);

The signed integer rightshift_U.In1 is shifted three bits to the right.

Generate Code That Does Not Allow Right Shifts on Signed Integers

  1. Open the Model Configuration Parameters dialog box and select the Code Style tab. Clear the Allow right shifts on signed integers parameter.

  2. Generate code for the model.

In the rightshift.c file, the rightshift_step function contains this code:

rightshift_Y.Out1 = (int16_T)asr_s32(rightshift_U.In1, 3U);

When you clear the Allow right shifts on signed integers parameter, the generated code contains a function call instead of a right shift on a signed integer. The function asr_s32 contains this code:

int32_T asr_s32(int32_T u, uint32_T n)
{
  int32_T y;
  if (u >= 0) {
    y = (int32_T)((uint32_T)u >> n);
  } else {
    y = -(int32_T)((uint32_T)-(u + 1) >> n) - 1;
  }
 
  return y;
}

The asr_s32 function casts a signed integer to an unsigned integer, and then right shifts the unsigned integer.

Related Topics