-2

I was trying to understand the bitwise operation and according to me integer contains 32 bit and from LSB 0th position to MSB 31st position so if I set left shift 1 to 31 place I think I should get 2^31 and the binary representation of it would be 10000000 00000000 00000000 00000000 so why in am getting the result as negative ? and please correct me if I am wrong.

#include<bits/stdc++.h>
using namespace std;
int main(){
    int i=1<<31;
    cout<<i;
    return 0;
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • Because out of 2147483648 combinations one of them goes for 0 :) – PTwr Jun 16 '17 at 10:22
  • 3
    `cout << std::numeric_limits::max()` – zett42 Jun 16 '17 at 10:24
  • 1
    If you have a (two's complement) N bits wide signed integer, it can represent values from `-2^(N-1)` to `2^(N-1)-1`. For your 32-bit integer the max value is `2^31-1`, which is `2147483647`. – HolyBlackCat Jun 16 '17 at 12:44

2 Answers2

0

Integer is a 32bit data type and its most significant bit stands for the sign. (That is the 32nd bit)

Therefore you're getting a negative value

amithad
  • 9
  • 2
  • 3
    You forgot to say "on some platforms" – Slava Jun 16 '17 at 12:40
  • An `int` only has 31 data bits. Shifting data into the 32nd bit invokes undefined behavior. There is no telling what result the OP will get. – Lundin Jun 16 '17 at 12:49
  • Specifically, this is true on platforms that use a two's-complement representation, which is most of them. (Well, except for the part about `int` being 32 bits. That's much more variable; `int` is allowed to have any length >= 16 bits.) – Cody Gray - on strike Jun 16 '17 at 12:49
  • Yes. On some platforms – amithad Jun 20 '17 at 08:51
0

C++ does not specify the behaviour of programs that include 1<<31.

On a different platform you may get a different answer, or a compilation error, or a program that formats your drive, or any other behaviour.

Caleth
  • 52,200
  • 2
  • 44
  • 75