﻿ 十进制转换二进制-vb.net_软件编程-脚本宝典

# 十进制转换二进制

## 十进制转换二进制

计算机是采用二进制存储的，计算机的二进制编码方式也分为原码，反码，补码方法。这是一个把十进制数字转换到它的二进制原码的算法，希望能给大家一些启发吧！这个算法我是用VB6写的，其中用到了函数递归调用和函数可选参数(个人感觉功能和C++中的函数重载差不多)。
--------------------------------------------------------------------------------
Option Explicit
Option Base 1

Dim S() As String * 1, i As Integer

Public Function BinaryConvertA(ByVal iNum As Integer, Optional ByVal iLength As Integer = 8) As String
//***************************************  Design By 0412Rainbow **********************************************//

的位数),可选,默认传递8,iNum的转换范围-2^(n-1) 到 +2^(n-1),返回值为二进制的字符串形式.

二进制位表示数据),则最高位是符号位,0表示正号,1表示负号;其余的n-1位表示数值的绝对值。

//****************************************************************************//

ReDim S(iLength) As String * 1
Dim sResult As String: i = 1: Dim j As Integer
If Abs(iNum) > 2 ^ (iLength - 1) Then
MsgBox "十进制数表示溢出", , "进制转换算法"
Exit Function
End If

If CStr(iNum) = "0" Then
For j = 1 To iLength
sResult = sResult & 0
Next
BinaryConvertA = sResult: Exit Function

End If

If Abs(iNum) <> iNum Then
S(iLength) = 1
Else
S(iLength) = 0
End If

Call ConvertToBinary(Abs(iNum), i)

For j = i + 1 To iLength - 1
S(j) = 0
Debug.Print j, S(j)
Next

For i = iLength To 1 Step -1
sResult = sResult & S(i)
Debug.Print sResult
Next
BinaryConvertA = sResult

End Function

Private Sub ConvertToBinary(ByVal iNums As Integer, ByVal iCount As Integer)
If iNums <> 1 Then
S(i) = iNums Mod 2
Debug.Print i, S(i)
i = i + 1
Call ConvertToBinary(iNums 2, i)
Else
S(i) = 1

End If
End Sub

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

Private Sub Command1_Click()
Text1.Text = Text1.Text & BinaryConvertA(111) & vbCrLf

End Sub

Private Sub Command2_Click()
Text1.Text = Text1.Text & BinaryConvertA(-222, 9) & vbCrLf

End Sub

Private Sub Command3_Click()
Text1.Text = ""

End Sub

Text1.Text = ""
Command1.Caption = "第一种调用方式"
Command2.Caption = "第二种调用方式"
Command3.Caption = "&clear"
End Sub

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

Tags：

﻿
<