Tobi3
Tobi3

Reputation: 147

Bitwise operations on negative numbers in C

What is the effect of the following?

unsigned int x = -1; x >>= 2;

I'm not quite sure what the x gets set to as it's a negative number and the type is unsigned?

Upvotes: 0

Views: 667

Answers (3)

Daniel Fischer
Daniel Fischer

Reputation: 183968

unsigned int x = -1;

sets x to UINT_MAX (section 6.3.1.3, point 2)¹. The int -1 is converted to unsigned int for the initialistaion of x. That conversion is done by adding (or subtracting, but not here) UINT_MAX +1 to the value until it is in the range 0 .. UINT_MAX, once here.

Thus x >>= 2; sets x to UINT_MAX/4, since bitwise right shift of unsigned integers is thus specified in section 6.5.7, point 5:

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2.

¹ "Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type."

Upvotes: 3

wildplasser
wildplasser

Reputation: 44250

It is an unsigned type initialised by a signed negative value. The shifting is still performed on an unsigned value.

Upvotes: 1

kratenko
kratenko

Reputation: 7592

The -1 should set an unsigned int to 0xffffffff, the highest number for that type (around 4.8 billion) -- or a lot higher if int has more than 32 bit.

Upvotes: 1

Related Questions