views:

59

answers:

1

Seeking to clarify something.

It is my understanding that with regard to arithmetical, logical bitwise shifts:

  1. << work the same for both
  2. >> shifts differ in which logical shift will always pad byte with 0, whereas arithmetical shift will pad it with the sign bit.

How can i differentiate this using C?

From what i understand, actual operators are the same <<,>>

How would command differ between:

int i=1;
printf ("%d\n", i >> 1); // logical shift

int j=1;
printf ("%d\n", j >> 1); // arithmetical shift

Please let me know,

+1  A: 

In case of nonnegative numbers, both kinds of right-shifts are the same. The difference appears only when the number to shift is negative.

Actually the C standard does not specify when should >> perform logical or arithmetic shift when the number is negative, but typically, it performs arithmetic shift. To perform logical shift, the number must be cast to the corresponding unsigned type, for example:

int x = -2;
int y = x >> 1;    // arithmetic shift.
assert (y == -1);
int z = (unsigned)x >> 1;  // logical shift.
assert (z == 0x7FFFFFFF);
KennyTM
Is there a way to force a particular shift. For instance, i'd like to (x<<1)>>1 in order to drop the "-" sign.
mac
@Jerry, @mac: See update.
KennyTM
@mac: Discarding the sign bit isn't the same as taking the absolute value in two's-complement.
jamesdlin
@jamesdlin . totally. don't know what i was thinking. Thanks.
mac
@KennyTM: yup, much improved.
Jerry Coffin
can you give me an example of arithmetic shift. I'm a bit confused.
Shweta