二进制转换为十进制使用数组和循环 [英] Convert Binary To Decimal Using Array and Loop

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

问题描述

我试图写一个VB函数,二进制转换为十进制。我需要二进制长度存储在数组中,并使用一个循环来找到我的答案。我一直在试图找出这出一段时间。这是我到目前为止,也许能帮到你。

 公共功能binaryToDecimal(二进制BYVAL作为字符串)
    昏暗myDecimal作为整数
    昏暗blength作为整数= Binary.Length
    昏暗指数(blength)作为整数
    对于指数=指数为0步骤-1
        myDecimal + =二进制*(2 ^(blength - 1))
        blength = blength - 1
    下一个
    返回myDecimal
结束功能


解决方案

我不明白你的code在所有...你从来没有填充数组与任何东西。无论怎么做,如果二进制字符串包含零,你做任何事情( 0 )。

但是,如果你想二进制转换为十进制,这里有一个简单的方法(你并不真的需要一个数组):

 公共功能BinaryToDecimal(二进制BYVAL作为字符串)作为整数
    昏暗返回值作为整数= 0
    暗淡x As中整数= 1
    对于i = Binary.Length - 1 0步骤-1
        如果Binary.Chars(ⅰ)=1C,则
            返回值+ = X
        万一
        X + = X
    下一个
    返回返回值
结束功能

该功能开始于字符串的结尾,去倒退。它增加 X 单独为每个字符,而返回值由电流 X <递增/ code>如果当前字符是'1'。

该函数将例如 1111 15 100000 32 1011101001 745

测试: http://ideone.com/SsZ3d2

希望这有助于!


编辑:

另外值得一提的是,该函数不支持字符串中的空格。如果你想要它做的是,只要告诉我,我会补充说了。

I am trying to write a VB function that converts binary to decimal. I need to store the binary length in an array and use a loop to find my answer. I have been trying to figure this out for a while. This is what I have so far maybe you can help.

Public Function binaryToDecimal(ByVal Binary As String)
    Dim myDecimal As Integer
    Dim blength As Integer = Binary.Length
    Dim index(blength) As Integer
    For index = index To 0 Step -1
        myDecimal += Binary * (2 ^ (blength - 1))
        blength = blength - 1
    Next
    Return myDecimal
End Function

解决方案

I don't understand your code at all... You never even fill the array with anything. Neither do you do anything if the binary string contains zeros (0).

But if you want to convert binary to decimal, here's a simple approach (and you don't really need an array):

Public Function BinaryToDecimal(ByVal Binary As String) As Integer
    Dim ReturnValue As Integer = 0
    Dim x As Integer = 1
    For i = Binary.Length - 1 To 0 Step -1
        If Binary.Chars(i) = "1"c Then
            ReturnValue += x
        End If
        x += x
    Next
    Return ReturnValue
End Function

The function starts at the end of the string and goes backwards. It increments x by itself for every char, and ReturnValue is incremented by the current x if the current character is '1'.

The function will convert for example 1111 into 15, 100000 into 32, and 1011101001 into 745.

Tested: http://ideone.com/SsZ3d2

Hope this helps!


EDIT:

It's also worth mentioning that the function does not support spaces in the string. If you want it to do that, just tell me and I'll add that too.

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

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