简体   繁体   中英

Shift with 64 bit int

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?

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.

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.

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.

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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