将二进制数转换为八进制数... [英] Convert Binary number to octal...

查看:165
本文介绍了将二进制数转换为八进制数...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受二进制数的代码。当我运行它并给出二进制数1011时,它给出521而不是13.所以,如何将二进制转换为八进制。以下是代码

-------------------------------------- -------------

 私有  Sub  Button2_Click(发件人作为系统。对象,e  As  System.EventArgs)句柄 Button2.Click 
Dim n,tmp,rm 作为
Dim cnt As 整数 = 0
Dim sum As Integer = 0
n = Val(txtnum.Text)
tmp = n
rm = 0
su m = 0
cnt = 0
tmp> 0
rm = tmp Mod 10
tmp \ = 10
sum = sum +(rm *(Pow( 8) ,cnt)))
cnt = cnt + 1
结束 虽然
txtoct.Text = sum.ToString()
结束 Sub

解决方案

有很多方法可以做到这一点,但我分两个阶段进行:

1)编写一个方法将二进制字符串转换为整数。

2)编写一个将整数转换为八进制的方法。



现在,有.NET方法可以做到这两点,但我认为这是你的功课?所以你必须自己编写它们?



首先编写占位符方法,使用.NET框架方法检查代码:

Convert.ToInt32 [ ^ ]将二进制字符串处理为整数

Convert.ToString [ ^ ]将转换指定基数中字符串的整数。



然后,您可以为每种方法编写自己的代码,并确保获得相同的结果!

 Convert.ToString(Convert.ToInt32(10011,2),8)


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

解决方案

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!


Convert.ToString(Convert.ToInt32("10011", 2),8)


这篇关于将二进制数转换为八进制数...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆