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

Realliferulorsays:RT @CodeSnippetsNET: How to check if a number is a power of 2 in C# and #VB .NET http://t.co/kSE4jSDnZv #dotnet #csharp #coding #visualbasi…

CodeSnippetBlogsays:RT @CodeSnippetsNET: How to check if a number is a power of 2 in C# and #VB .NET http://t.co/kSE4jSDnZv #dotnet #csharp #coding #visualbasi…

AllCodeSnippetssays:RT @CodeSnippetsNET: How to check if a number is a power of 2 in C# and #VB .NET http://t.co/kSE4jSDnZv #dotnet #csharp #coding #visualbasi…