Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

c++ - Left Shifting a number

i performed a simple bit operation using << on the variable result to set bit on the 32nd position..

result = result | (1<<31);

which should give the output as(in binary):

0000000000000000000000000000000010000000000000000000000000000000

and in decimal:

2147483648

but instead this was the output(in binary):

1111111111111111111111111111111110000000000000000000000000000000

and in decimal:

-2147483648

here is the code:

#include <bitset>
#include <iostream>
int main() {
  int64_t result = 0;
  
  result = result | (1 << 31);  
  std::bitset<64> x(result);
  std::cout << x <<std:: endl;
  std::cout << result << std:: endl;
}

please help me find the error


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The literal 1 is treated as int. It seems int in your environment is 32-bit long and the result is sign-extended.

Add cast to int64_t before shifting to calculate in int64_t.

#include <bitset>
#include <iostream>
int main() {
  int64_t result = 0;
  
  result = result | (static_cast<int64_t>(1) << 31);  
  std::bitset<64> x(result);
  std::cout << x <<std:: endl;
  std::cout << result << std:: endl;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...