Home >>VB.Net Programs >VB.Net program to print the total bits required to store a given integer number

VB.Net program to print the total bits required to store a given integer number

Total bits required to store a given integer number in VB.Net

Here, we'll calculate how many bits a given number stored in memory using bitwise operators and printing on the console screen.

Program

Below is the source code to print the total bits necessary for storing a given integer number. The program given is compiled and successfully executed.

Example


Module Module1
    Sub Main()
        Dim iLoop As Integer
        Dim num As Integer
        Dim countBits As Integer = 0

        Console.Write("Enter Your Number : ")
        num = Integer.Parse(Console.ReadLine())

        For iLoop = 0 To 31 Step 1
            If ((1 << iLoop) And num) Then
                countBits = iLoop + 1
            End If
        Next

        Console.Write("Total bits required to store for {0} are:{1}", num, countBits)

        Console.ReadLine()
    End Sub
End Module

Output:
Enter Your Number: 127
Total bits required to store for 127 are:7

Explanation:

Here, we generated a Module1 module that contains a method called Main(). And, we created iLoop, num, and countBits, three local variables. After that, we entered a number and then, using bitwise AND and bitwise left-shift operators, we checked each bit of a given number and calculated the total bits needed to store a given number and then printed the count on the console screen.


No Sidebar ads