How to check if a number is a power of 2 in C# and VB.NET

To check if a number is a power of 2 in C# and VB.NET you can use the following extension method.

Sample C#

public static bool IsPowerOfTwo(this ulong input)
{
    return (input != 0) && ((input & (input - 1)) == 0);
}

Sample VB.NET

<System.Runtime.CompilerServices.Extension> _
Public Shared Function IsPowerOfTwo(input As ULong) As Boolean
	Return (input <> 0) AndAlso ((input And (input - 1)) = 0)
End Function

As always, the extension method was added to out Fesslersoft.Extensions library @Github

Please rate this snippet

How to calculate PercentOf in PHP

To calculate PercentOf in PHP you can use the following snippet. It will calculate the percent of 2 given integers.

Sample PHP

Function PercentOf($int1, $int2) { 
	if ($int2 <= 0 || $int1 <=0){
		return 0;
	}
    $val1 = $int1 / $int2;  
    $retVal = $val1 * 100;  
    return $retVal;  
} 

If there is a 0 passed it will return 0.

Please rate this snippet