user93868 - 3 months ago 11

C Question

Is there a simple way to do logical right shift in c for negative numbers like how we have >> for arithmetic right shift?

Answer

Right-shifting negative numbers invoke implementation-defined behavior in C. What will happen is not specified by the standard, but left to the compiler to specify. So it can either result in an arithmetic shift, or a logical shift, or perhaps something else entirely (like rotation, though I've never heard of that). You can't know or assume which method that applies on your compiler, unless you read the specific compiler documentation.

Unsigned numbers always use logical shift however. So if you want logical shift on a negative number, portably, then convert to unsigned before the shift:

```
int32_t i = -1;
i = (int32_t) ((uint32_t)i >> n); // guaranteed to give logical shift
```

Similarly, if you want to guarantee an arithmetic shift:

```
int32_t i = -1;
bool negative = i < 0;
if(negative)
{
i = -i;
}
i = (int32_t) ((uint32_t)i >> n);
if(negative)
{
i = -i;
}
```