简体   繁体   中英

Bitwise Shift Clarification

Assume I have the variable x initialized to 425 . In binary, that is 110101001 .

Bitshifting it to the right by 2 as follows: int a = x >> 2; , the answer is: 106 . In binary that is 1101010 . This makes sense as the two right-most bits are dropped and two zero's are added to the left side.

Bitshifting it to the left by 2 as follows: int a = x << 2; , the answer is: 1700 . In binary this is 11010100100 . I don't understand how this works. Why are the two left most bits preserved? How can I drop them?

Thank you,

This is because int is probably 32-bits on your system. (Assuming x is type int .)

So your 425 , is actually:

0000 0000 0000 0000 0000 0001 1010 1001

When left-shifted by 2, you get:

0000 0000 0000 0000 0000 0110 1010 0100

Nothing gets shifted off until you go all the way past 32. (Strictly speaking, overflow of signed-integer is undefined behavior in C/C++.)

To drop the bits that are shifted off, you need to bitwise AND against a mask that's the original length of your number:

int a = (425 << 2) & 0x1ff;  //  0x1ff is for 9 bits as the original length of the number.

First off, don't shift signed integers. The bitwise operations are only universally unambiguous for unsigned integral types.

Second, why shift if you can use * 4 and / 4 ?

Third, you only drop bits on the left when you exceed the size of the type. If you want to "truncate on the left" mathematically, perform a modulo operation:

(x * 4) % 256

The bitwise equivalent is AND with a bit pattern: (x << 2) & 0xFF

(That is, the fundamental unsigned integral types in C are always implicitly "modulo 2 n ", where n is the number of bits of the type.)

Why would you expect them to be dropped? Your int (probably) consumes 4 bytes. You're shifting them into a space that it rightfully occupies.

The entire 4-byte space in memory is embraced during evaluation. You'd need to shift entirely out of that space in memory to "drop" them.

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