Kevin Hu
Kevin Hu

Reputation: 31

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?

Upvotes: 2

Views: 136

Answers (3)

Petr Skocik
Petr Skocik

Reputation: 60143

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 / 2E2 . 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).

Upvotes: 2

Stephan Lechner
Stephan Lechner

Reputation: 35164

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.

Upvotes: 1

jxh
jxh

Reputation: 70502

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).

Upvotes: 1

Related Questions