简体   繁体   中英

C-language binary shift operator

I'm trying to learn some basic C for a project. On the Wikipedia article on binary shift operators:

If the variable ch contains the bit pattern 11100101, then ch >> 1 will produce the result 01110010, and ch >> 2 will produce 00111001.

Just for clarification, will the last digit of the binary operator be lost if you shift it to the right (>>1)? It won't rotate to the front, like in a circular array, correct?

Here's what the holy word of C (the C standard) says about bitshifts to the right:

6.5.7p5 :

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2 E2 . If E1 has a signed type and a negative value, the resulting value is implementation-defined.

In other words: x>>n == x/two_to_the(n) , though that may not be the case if x<0

(To answer even more directly, yes — when you divide, the least significant bits are lost).

Yes.

The shift operation x >> 1 will result in a value equal to x divided by 2 if x is unsigned or positive, and is implementation-defined if x is negative (C.2011 §6.5.7 ¶5).

Right, the outermost bit will be lost unless you save its value before shifting:

unsigned char ch = 229; 
int lostBit = ch & 0x01;
ch >>= 1;

Note that bit shift operator >> is defined only for unsigned or positive values. In your example, if ch were a signed char, a value 11100101 actually represented a negative number (-27) and the operation would yield undefined behaviour.

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