B.Balamanigandan - 1 month ago 4x

C# Question

I want to **get the Sign of a Number without a Logical Statement**. Already a predefined method is available

`Math.Sign()`

The Tried C# Code:

`public int GetSign(int value)`

{

int bitFlag = 1;

var m = Convert.ToString(value, 2);

int length = m.Length;

if (m[length - 1] == '1')

{

bitFlag = -1;

}

return bitFlag;

}

Condition:

- If the Last bit is then return
`1`

`-1`

- If the Last bit is then return
`0`

`1`

Kindly assist me, how to remove the above

`IF`

Answer

Interesting thing about bit shifting: If you right shift the bits, the leading bit will be propagated to the right.

Example byte : 10000000 Example byte >> 1 : 11000000

Integers take 32 bytes to represent. So what happens if we shift the bits by 31 places? The leading bit will always be propagated, meaning all positive numbers will become 0 and all negative numbers will become -1.

Therefore :

```
public static int signOfInt(int input)
{
return (input >> 31);
}
```

will return 0 for positive numbers and -1 for negative numbers.

Source (Stackoverflow)

Comments