用设定最显著位 [英] set most significant bit in C
问题描述
我试图创下最显著位在长隆符号,X。
要做到这一点,我使用这行code的:
I am trying to set the most significant bit in a long long unsigned, x. To do that I am using this line of code:
x |= 1<<((sizeof(x)*8)-1);
我想这应该工作,因为sizeof的字节大小给人,所以我再乘以8,并减去一个设置最后一位。每当我这样做,编译器有这样的警告:警告:类型的左移计数> =宽度
I thought this should work, because sizeof gives size in bytes, so I multiplied by 8 and subtract one to set the final bit. Whenever I do that, the compiler has this warning: "warning: left shift count >= width of type"
我不明白为什么这个错误发生。
I don't understand why this error is occurring.
推荐答案
的 1
您移行类型的常量 INT
,这意味着你被的sizeof(无符号长长)* 8)移位的
位。这种转变可以很容易地超过 INT
值 - 1 INT
的宽度,这显然是在您的情况发生了什么事了。
The 1
that you are shifting is a constant of type int
, which means that you are shifting an int
value by sizeof(unsigned long long) * 8) - 1
bits. This shift can easily be more than the width of int
, which is apparently what happened in your case.
如果你想获得无符号长长
类型的某些位掩码面具,你应该的初始位掩码无符号长启动长
类型,而不是 INT
键入
If you want to obtain some bit-mask mask of unsigned long long
type, you should start with an initial bit-mask of unsigned long long
type, not of int
type.
1ull << (sizeof(x) * CHAR_BIT) - 1
这是可以说是更好的方式来构建相同的面具将
An arguably better way to build the same mask would be
~(-1ull >> 1)
或
~(~0ull >> 1)
这篇关于用设定最显著位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!