简体   繁体   English

警告:左移计数> =类型的宽度

[英]warning: left shift count >= width of type

I'm very new to dealing with bits and have got stuck on the following warning when compiling: 我很擅长处理比特,并且在编译时遇到以下警告:

  7: warning: left shift count >= width of type 

My line 7 looks like this 我的第7行看起来像这样

unsigned long int x = 1 << 32;

This would make sense if the size of long on my system was 32 bits. 如果我的系统上的long为32位,这将是有意义的。 However, sizeof(long) returns 8 and CHAR_BIT is defined as 8 suggesting that long should be 8x8 = 64 bits long. 但是, sizeof(long)返回8CHAR_BIT定义为8 ,表示long应为8x8 = 64位长。

What am I missing here? 我在这里错过了什么? Are sizeof and CHAR_BIT inaccurate or have I misunderstood something fundamental? sizeofCHAR_BIT不准确的还是我误解了一些基本的东西?

long may be a 64-bit type, but 1 is still an int . long可能是64位类型,但1仍然是int You need to make 1 a long int using the L suffix: 你需要使用L后缀使1long int

unsigned long x = 1UL << 32;

(You should also make it unsigned using the U suffix as I've shown, to avoid the issues of left shifting a signed integer. There's no problem when a long is 64 bits wide and you shift by 32 bits, but it would be a problem if you shifted 63 bits) (你应该使用U后缀使其unsigned ,如我所示,以避免左移有符号整数的问题。当long 64位宽并且你移位32位时没有问题,但它会是一个你移63位的问题)

unsigned long is 32 bit or 64 bit which depends on your system. unsigned long是32位还是64位,具体取决于您的系统。 unsigned long long is always 64 bit. unsigned long long总是64位。 You should do it as follows: 你应该这样做:

unsigned long long x = 1ULL << 32

unsigned long x = 1UL << 31; unsigned long x = 1UL << 31;

Not show the error message. 不显示错误消息。 Because before you specify the 32, is not true because only limited to 0-31. 因为在你指定32之前,不是因为仅限于0-31。

You can't shift a value to its max bit 您不能将值移动到其最大位

int x;         // let int be 4 bytes so max bits : 32 
x <<= 32; 

So, this generates the warning 所以,这会产生警告

left shift count >= width of type (ie type = int = 32 )

The accepted solution is fine for [constant]ULL<<32 but no good for existing variables - eg [variable]<<32. 接受的解决方案适用于[常量] ULL << 32但对现有变量没有好处 - 例如[变量] << 32。 The complete solution for variables is: ((unsigned long long)[variable]<<32). 变量的完整解决方案是:((unsigned long long)[variable] << 32)。 Aside: My personal opinion of this warning is that it is totally unnecessary in the first place. 旁白:我个人对此警告的看法是,首先完全没有必要。 The compiler can see what the receiving data type is and knows the width of the parameters from the definitions in headers or constant values. 编译器可以查看接收数据类型是什么,并从头部或常量值中的定义中了解参数的宽度。 I believe Apple could make the clang compiler a little more intelligent than it is regarding this warning. 我相信Apple可以使clang编译器比这个警告更加智能。

You can use something like that: 你可以使用这样的东西:

unsigned long x = 1;
x = x << 32;

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

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