Posted on by Kalkicode
Code Conversion

Conversion from binary to octal in vb.net

Vb program for Conversion from binary to octal. Here mentioned other language solution.

' Include namespace system
Imports System 
'  Vb.net program for
'  Convert Binary number into Octal number
public Class Convert
    ' Convert decimal number into octal
    Public Function  octal(ByVal number As Integer) As Integer
        Dim result As Integer = 0
        Dim multiplier As Integer = 1
        Dim remainder As Integer = 0
        while (number <> 0)
            remainder = number Mod 8
            result = (remainder * multiplier) + result
            multiplier *= 10
            number = (number / 8)
        End While
        Return  result
    End Function
    Public Sub binaryToOctal(ByVal num As String)
        if (num.Length = 0) Then
            ' When empty binary number
            Return
        End If
        ' Some useful variable
        Dim flag As Boolean = False
        Dim decimalNo As Integer = 0
        Dim counter As Integer = 0
        Dim index As Integer = num.Length - 1
        ' We Assume that given binary number is valid
        ' Here - indicates negative binary number
        ' First convert binary to decimal
        ' Example = 10111 => 23
        while (index >= 0)
            if (num(index) = "1"c) Then
                decimalNo += (1 << counter)
            ElseIf (num(index) <> "0"c) Then
                    if (index = 0 AndAlso num(index) = "-"c) Then
                        ' When get negative number
                        flag = True
                    Else
                        ' Not a valid binary number
                        Return
                    End IF
                End If
            counter += 1
            index -= 1
        End While
        ' When given number is 
        Dim output As Integer = Me.octal(decimalNo)
        if (flag = True) Then
            output = -output
        End If
        ' Display given number
        Console.Write("Binary : " + num)
        ' Display result
        Console.WriteLine(" Octal : " + output.ToString())
    End Sub
    Public Shared Sub Main(ByVal args As String())
        Dim task As Convert = New Convert()
        ' Test Case
        task.binaryToOctal("1111")
        task.binaryToOctal("10111")
        task.binaryToOctal("101011")
        task.binaryToOctal("11011")
        task.binaryToOctal("-1000110")
    End Sub
End Class

Output

Binary : 1111 Octal : 27
Binary : 10111 Octal : 37
Binary : 101011 Octal : 153
Binary : 11011 Octal : 33
Binary : -1000110 Octal : -116

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment