Shift with 64 bit int

旧街凉风 提交于 2019-12-11 13:38:23

问题


I have a __int64 variable x = 0x8000000000000000.

I try to shift it right by byte : x >> 4

I`ve thought that the result should be 0x0800000000000000, but unfortunately I get 0xf800000000000000.

I use VS10. Why is it so? And how can I solve that?


回答1:


The reason is because shifting signed numbers is only defined by the language if the left operand is at least 0. In your case I assume it's a twos-complement representation and your number is negative making the result unspecified (or implementation-defined, I don't have the reference at hand right now). Typically you would either get a logical shift or an arithmetic shift.

If you can get away with making your variable unsigned that would solve your problem.




回答2:


try to use __uint64 variable x = 0x8000000000000000

I think you can declare it this way as well:

u64 x = 0x8000000000000000;

x >> 4 you will give you:

0x0800000000000000

see for more info where the F came from in the MSBs.




回答3:


Well, that is an easy one. :)

Your number is signed. With the first bit being set, it is negative. Thus, in order to keep it negative, it is filled with 1s.

I would assume casting it to unsigned and then shifting it should fix your problem.




回答4:


This is because you have a negative number. Use (or convert to) unsigned before the shift.




回答5:


Signed values are shifted right by sign bit and unsigned by zero:

int _tmain(int argc, _TCHAR* argv[])
{
    __int64  signedval;
    unsigned __int64  unsignedval;

    signedval=0x8000000000000000 >> 4;
    unsignedval=0x8000000000000000 >> 4;

        printf(" Signed %x  , unsigned %x   \n", signedval, unsignedval);

        getchar();

    return 0;
}

and the output is:

Signed 0  , unsigned 8000000 


来源:https://stackoverflow.com/questions/14614877/shift-with-64-bit-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!