Daniel
Daniel

Reputation: 93

Seeking explanation of how shifting bits can verify the sign of a number

I have this excerpt from geeksforgeeks, assume x and y are integers.

“If (x-y) is smaller than 0, then (x -y)>>31 will be 1. If (x-y) is greater than or equal to 0, then (x -y)>>31 will be 0.”

I’m curious to know why this is the case.

Upvotes: 0

Views: 23

Answers (2)

mCoding
mCoding

Reputation: 4859

The quote is assuming a 32-bit two's complement representation of integers (this is the most common representation of integers, though using 64 bits is becoming more common). In particular, of the 32 bits used to represent an integer, the highest order bit is used to represent whether the integer is negative or positive. Highest bit = 1 means negative, highest bit = 0 means non-negative. Thus, if you compute (x-y) and the 32nd bit tells you whether x >= y (32nd bit = 0) or x < y (32nd bit = 1). So how do you get the 32nd bit? Shift right 31 times.

Upvotes: 0

Axel Kemper
Axel Kemper

Reputation: 11322

This is the case for signed 32-bit integers in two's complement form.

The sign-bit is the most significant bit. The shift operation >>31 will shift the sign-bit to the least significant bit position. A 1 indicates, that the difference is negative.

Upvotes: 1

Related Questions