简体   繁体   English

在Ruby和C ++中,左移位16

[英]Left bit shift by 16 in Ruby and C++

I have the following code in Ruby. 我在Ruby中有以下代码。

x = 33078
x << 16
# => 2167799808

In C++ That code is 在C ++中代码是

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? 我知道这与溢出有关,但我怎样才能让C ++给出与Ruby相同的结果?

33078 << 16 does not fit into an integer and that is why in C++ it overflows and gets to a negative value. 33078 << 16不适合整数,这就是为什么在C++它会溢出并变为负值。 Meanwhile in ruby the type is automatically converted to something big enough to store the result of this computation. 同时在ruby中,类型会自动转换为足以存储此计算结果的大小。

If you want to be able to compute this value in C++ , use a type with higher max value. 如果您希望能够在C++计算此值,请使用具有更高最大值的类型。 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 . 在这种情况下, unsigned int就足够了,但是如果你想计算更大的值,你可能需要long long甚至unsigned long long

You need to use an integer that is the same byte size as a Ruby int. 您需要使用与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 ). 通常,C中的int是32位,而不是64位(或8字节)。

#include <iostream>

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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