B.Balamanigandan B.Balamanigandan - 2 months ago 12
C# Question

Get Sign of a Number without Logical Statement in C#

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

Math.Sign()
. But I need to Implement in my own style.

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
    1
    then return
    -1

  • If the Last bit is
    0
    then return
    1



Kindly assist me, how to remove the above
IF
Statement...

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.