Zvnoky Brown Zvnoky Brown - 1 year ago 82
C Question

How it is possible to turn unsigned int to negative number with bit shift?

Why do i get negative number when executing this?

unsigned int a = 1 << 31;

I already checked size of integer on my computer and it is 4 Bytes. So my integer number is consisted of 32 bits and doing 31 shifts to the left I should get until the most significant bit. That means that it should be positive number, but i always get negative.

What I get : -2147483648

What I expected : Some positive number ( probably 1073741824)

What am I missing here?

Answer Source

The problem isn't the fact that you're bit shifting. You are simply not printing in the corresponding format.

%d or %i is for printing int, and thus when you try to print your unsigned int, it is converted into an signed int.

See here: What is the format specifier for unsigned short int?

or https://www.le.ac.uk/users/rjm1/cotter/page_30.htm

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download