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 Share us:
Please rate this snippet

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

Leave a Reply