0

Why do i get negative number when executing this?

unsigned int a = 1 << 31;
printf("%d",a);

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?

Zvnoky Brown
  • 137
  • 2

3 Answers3

0

Use %u as the printf format string.

Meaning:

printf("%u",a);
Ehsan
  • 1,338
  • 14
  • 13
0

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

Community
  • 1
  • 1
Subbies
  • 246
  • 2
  • 8
0

In addition to the wrong format specifier you're using (%d instead of %u), you're probably invoking undefined behaviour by shifting a 1 into the sign bit of the int operand, as stated in this answer.
To fix it, use an unsigned literal:

unsigned int a = 1u << 31;
//                ^
Community
  • 1
  • 1
Quentin
  • 62,093
  • 7
  • 131
  • 191