Dan Grahn
Dan Grahn

Reputation: 9424

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?

Upvotes: 3

Views: 298

Answers (3)

nurettin
nurettin

Reputation: 11746

#include <iostream>

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

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

Upvotes: 0

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 ).

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70989

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.

Upvotes: 5

Related Questions