14,489,111 members
Rate this:
See more:
I Have a code that accepts binary number. When I run it and give binary number 1011 it gives 521 instead of 13. So, how to convert binary to octal. Below is the code
---------------------------------------------------
```Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim n, tmp, rm As Long
Dim cnt As Integer = 0
Dim sum As Integer = 0
n = Val(txtnum.Text)
tmp = n
rm = 0
sum = 0
cnt = 0
While tmp > 0
rm = tmp Mod 10
tmp \= 10
sum = sum + (rm * (Pow(8, cnt)))
cnt = cnt + 1
End While
txtoct.Text = sum.ToString()
End Sub```
Posted
manchanx 10-Mar-15 11:30am

Did you try using the Debugger?
A94 10-Mar-15 11:38am

yes...I tried

Rate this:

## Solution 1

There are a huge number of ways to do this, but I'd do it in two stages:
1) Write a method to convert a binary string to an integer.
2) Write a method to convert an integer to Octal.

Now, there are .NET methods that will do both of those, but I assume this is your homework? So you have to write them yourself?

So start by writing "placeholder" methods which use the .NET framework methods to check your code:
Convert.ToInt32[^] will handle binary string to integer
Convert.ToString[^] will convert an integer to a string in the specified base.

Then, you can just write your own code for each method and make sure you get the same results!
Rate this:

## Solution 2

```Convert.ToString(Convert.ToInt32("10011", 2),8)
```
A94 10-Mar-15 11:53am

Can you help me to understand the above line of code. Please.
John C Rayan 10-Mar-15 11:57am

The first Convert.ToInt32 takes the form("Binary Number" , fromBase) so it converts the binary to integer first. The second Convert takes the form Convert.ToString(integer , toBase) so the converted integer from binary converted to base 8 which is octal. Hope this makes sense.
A94 10-Mar-15 12:03pm

OK, I understood. But which data type should I use to enter binary number of any length(i.e I should convert binary number of any length to its appropriate type)
John C Rayan 10-Mar-15 12:20pm

Use string and check if it is a valid number before change it to a number.