How do I check if a number is positive or negative in C#?
if (num < 0) {
//negative
}
if (num > 0) {
//positive
}
if (num == 0) {
//neither positive or negative,
}
or use "else ifs"
For a 32-bit signed integer, such as System.Int32
, aka int
in C#:
bool isNegative = (num & (1 << 31)) != 0;
Native programmer's version. Behaviour is correct for little-endian systems.
bool IsPositive(int number)
{
bool result = false;
IntPtr memory = IntPtr.Zero;
try
{
memory = Marshal.AllocHGlobal(4);
if (memory == IntPtr.Zero)
throw new OutOfMemoryException();
Marshal.WriteInt32(memory, number);
result = (Marshal.ReadByte(memory, 3) & 0x80) == 0;
}
finally
{
if (memory != IntPtr.Zero)
Marshal.FreeHGlobal(memory);
}
return result;
}
Do not ever use this.
This code takes advantage of SIMD instructions to improve performance.
public static bool IsPositive(int n)
{
var v = new Vector<int>(n);
var result = Vector.GreaterThanAll(v, Vector<int>.Zero);
return result;
}
OVERKILL!
public static class AwesomeExtensions
{
public static bool IsPositive(this int number)
{
return number > 0;
}
public static bool IsNegative(this int number)
{
return number < 0;
}
public static bool IsZero(this int number)
{
return number == 0;
}
public static bool IsAwesome(this int number)
{
return IsNegative(number) && IsPositive(number) && IsZero(number);
}
}
int j = num * -1;
if (j - num == j)
{
// Num is equal to zero
}
else if (j < i)
{
// Num is positive
}
else if (j > i)
{
// Num is negative
}