# Shift operators

Niyas Ahmed Sheikh

Ranch Hand

Posts: 129

posted 11 years ago

11111111111111111111111111010110 (-42)

11111111111111111111111111101011 (-42 >> 1)

11111111111111111111111111110101 (-42 >> 2)

11111111111111111111111111111010 (-42 >> 3)

11111111111111111111111111111101 (-42 >> 4)

11111111111111111111111111111110 (-42 >> 5)

The bits on the right side fall off into the bit bucket as they're shifted off. The >> retains the value of the sign bit.

Hope this helps.

[ September 01, 2005: Message edited by: Steve Morrow ]

11111111111111111111111111101011 (-42 >> 1)

11111111111111111111111111110101 (-42 >> 2)

11111111111111111111111111111010 (-42 >> 3)

11111111111111111111111111111101 (-42 >> 4)

11111111111111111111111111111110 (-42 >> 5)

The bits on the right side fall off into the bit bucket as they're shifted off. The >> retains the value of the sign bit.

Hope this helps.

[ September 01, 2005: Message edited by: Steve Morrow ]

posted 11 years ago

Negative numbers are stored in binary form as two's complement.

So -42 is: 11010110 (expressed as an 8-bit two's complement number)

When you shift the number right, the sign bit (the leftmost bit) will be extended, so -42 >> 5 gives you: 11111110, which is -2.

So -42 is: 11010110 (expressed as an 8-bit two's complement number)

When you shift the number right, the sign bit (the leftmost bit) will be extended, so -42 >> 5 gives you: 11111110, which is -2.