' 用途:将二进制转化为十进制 ' 输入:Bin(二进制数) ' 输入数据类型:String
' 输出:BIN_to_DEC(十进制数) ' 输出数据类型:Long
' 输入的最大数为1111111111111111111111111111111(31个1),输出最大数为2147483647
Public Function BIN_to_DEC(ByVal Bin As String) As Long Dim i As Long
For i = 1 To Len(Bin)
BIN_to_DEC = BIN_to_DEC * 2 + Val(Mid(Bin, i, 1)) Next i
End Function
比如输入:1010
输出就是:10
进制转换并不是那么难的,有很多相关的资料。
提供一个二进制转化为十进制的函数Private Sub command1_click()
MsgBox BIN_to_DEC("11")
End Sub
Private Function BIN_to_DEC(ByVal Bin As String) As Long
Dim i As Long
For i = 1 To Len(Bin)
BIN_to_DEC = BIN_to_DEC * 2 + Val(Mid(Bin, i, 1))
Next i
End Function
'没有特定的函数。一般都是程序员自己编写自定义函数,无轮写法怎样都是用到了循环过程,请参考:'如方法一:
'返回二进制数对应的十进制数值
Public Function B2D(ByVal bstr As String) As Long
Dim n As Integer
Dim s As Long
Dim i As Integer
Dim w As Integer
n = Len(Trim(bstr)) '去掉字串首尾可能有的空格并测出字串的长度
s = 0 '累加器清零
For i = n To 1 Step -1 '依次取字串的各位
w = Val(Mid(bstr, i, 1))'把每位字符转换为数值,非法字符将视为0
s = s + 2 ^ (n - i) * w '按位计权累加
Next i
B2D = s '返回累加值
End Function
'返回十进制数对应的二进制字串
Public Function D2B(ByVal Dnum As Long) As String
Dim xx As String
Dim yy As Integer
xx = "" '字串累加清空
Do While Dnum >0 '循环取余至小于1
yy = Dnum Mod 2 '除2取余
Dec = Dec \ 2 '除2取整
xx = Trim(Str(yy)) &xx '字串累加
Loop
D2B = xx '返回字串
End Function
'方法二:
'返回二进制数对应的十进制数值
Private Function C2to10(n2 As String) As Long
Dim i As Long, lenn2 As Long, n10 As Long
lenn2 = Len(n2)
For i = 1 To lenn2
n10 = n10 + Mid(n2, lenn2 - i + 1, 1) * 2 ^ (i - 1)
Next i
C2to10 = n10
End Function
'返回十进制数对应的二进制字串
Private Function C10to2(n10 As Long) As String
Dim n2 As String
Do Until n10 = 0
n2 = n10 Mod 2 &n2
n10 = n10 \ 2
Loop
C10to2 = n2
End Function
请参考。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)