简体   繁体   中英

Left bit shift by 16 in Ruby and C++

I have the following code in Ruby.

x = 33078
x << 16
# => 2167799808

In C++ That code is

int x = 33078;
x << 16
# => -2127167488

I know this has to do with overflows, but how can I get the C++ to give the same result as Ruby?

33078 << 16 does not fit into an integer and that is why in C++ it overflows and gets to a negative value. Meanwhile in ruby the type is automatically converted to something big enough to store the result of this computation.

If you want to be able to compute this value in C++ , use a type with higher max value. unsigned int will be enough in this case but if you want to compute bigger values you may need long long or even unsigned long long .

You need to use an integer that is the same byte size as a Ruby int.

 pry(main)>   x = 33078
=> 33078
 pry(main)> x.size
=> 8

Try

 long int x

Generally int's in C are 32bit, not 64bit ( or 8 bytes ).

#include <iostream>

int main()
{
  uint64_t x= 33078;
  std::cout<< (x<< 16);
}

$ g++ -std=c++11 test.cpp && ./a.out
$ 2167799808

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM