But when we use the signed variable and the shift operation we must consider the singed bit.See the below example code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int 8_t b = -10; // b = 0xf6 for 2's complement | |
b = b << 1; // b=0xec | |
b = b >> 1; // Now b = 0x76 and for demical b = 118 unexpect ouput | |
// The correct way to do that operation | |
b = b&0x80 | b>>1;// b = 0xf6 for demical b = 10 |
Ref:
1.Logical Vs. Arithmetic Shift
2.C语言中的逻辑右移和算术左移