B.Balamanigandan B.Balamanigandan - 1 year ago 97
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

. 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;


  • If the Last bit is
    then return

  • If the Last bit is
    then return

Kindly assist me, how to remove the above

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download