user3778242
user3778242

Reputation: 183

What's wrong with this logical shift right in C

I made this small program just to get an idea of how to do logical shifting right in C.

#include <stdio.h>

int main (void)
{
    int n=-2,t;
    t = (int)((unsigned int)n >> 1);
    printf("%d\n",t);
    return 0;
}

However, it outputs
2147283747. Am I missing something here? Shouldn't the answer be 7?

Upvotes: 2

Views: 239

Answers (1)

M.M
M.M

Reputation: 141534

In C, right-shift of non-negative integral values (either any value of an unsigned type, or any non-negative value of a signed type) is defined as integer division by 2.

Conversion from negative values of int to unsigned int is also well-defined: n wraps around modulo UINT_MAX+1. On typical systems with 32-bit int, UINT_MAX == 4294967295.

So (unsigned int)n is 4294967294. Perform the right-shift on this is division by 2, giving 2147483647. Since that is a valid int, the conversion to int leaves the value unchanged and this should be what you see.

I presume that your 2147283747 is a typo for 2147483647 ?

Upvotes: 7

Related Questions