简体   繁体   中英

Left bit shift operation in C

I'm trying to shift the variable 'a' that has a value 1111 and shift it to the left so I could get 1110 meaning it should print the number 14. However, it is printing 30. I'm thinking that because it is shifting but it doesn't take the most left bit out (11110) but it should have been 1110. Here is my code. Thank you.

int main(int argc, char *argv[]) {
unsigned a;
a=0xF;
a=a<<1; 
printf(": %u\n",a);

Your a variable is declared as unsigned -- this means it is an unsigned int , which usually has 32 bits. So when you put 0xF into it, it really contains 0x0000000F , or

00000000000000000000000000001111

in binary.

When you shift that one position to the left, it contains

00000000000000000000000000011110

or 30 in decimal. (0x1e in hex)

If you want to restrict it to just 4 bits, you'll want to AND the result with 0xF after every shift operation, like

a = a << 1;
a = a & 0xF;

That will result in a containing just 1110 (but really containing 00000000000000000000000000001110 )

First of all, unsigned is short for unsigned int and on most modern systems, an int is defined to be 4 bytes (32 bits). In any case, it's certainly more than 4 bits.

You are right in that "it doesn't take the most left bit out".

If you want you can bitwise & it with 0xF which will set any bits to the left of the last 4 bits to 0 .

a = (a << 1) & 0xF;

When you left shift a number the left most bit is not dropped it just moves to the left. So, when you left shift 1111 you will get 11110. For convenience, you can remember that whenever you left shift a number it is multiplied by 2 and when you right shift it you are in fact dividing it by 2.The drop would occur only if the type of bits that you have assigned run out for that number. In this case you will get garbage values as an answer. So your output is correct in context with what you are doing. But if you want to get 14 from 15, I suggest you use subtraction.

Shifting 1111 to the left would result in 11110, which is indeed 30. Try reading this really good answer to a related question, I Think you got the wrong idea of bit shifting. What are bitwise shift (bit-shift) operators and how do they work?

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