## CSDN博客

### 字符串与二进制互相转化（不包含汉字)

rem 此程序由Qthinker制作，免费发布，可以修改，请保留此信息
Option Base 1
Private Function byte2bit(s As String) As String
Dim i As Integer, j As Integer, k As Integer, ilen As Integer
Dim by() As String
Dim b() As Integer
ilen = Len(s)
ReDim by(ilen)
ReDim b(ilen / 8)
For k = 1 To ilen
by(k) = Mid$(s, k, 1) Next k For i = 1 To (ilen / 8) If by(1 + 8 * (i - 1)) = "1" Then b(i) = b(i) Or &H80 Else b(i) = b(i) And &H7F End If If by(2 + 8 * (i - 1)) = "1" Then b(i) = b(i) Or &H40 Else b(i) = b(i) And &HBF End If If by(3 + 8 * (i - 1)) = "1" Then b(i) = b(i) Or &H20 Else b(i) = b(i) And &HDF End If If by(4 + 8 * (i - 1)) = "1" Then b(i) = b(i) Or &H10 Else b(i) = b(i) And &HEF End If If by(5 + 8 * (i - 1)) = "1" Then b(i) = b(i) Or &H8 Else b(i) = b(i) And &HF7 End If If by(6 + 8 * (i - 1)) = "1" Then b(i) = b(i) Or &H4 Else b(i) = b(i) And &HFB End If If by(7 + 8 * (i - 1)) = "1" Then b(i) = b(i) Or &H2 Else b(i) = b(i) And &HFD End If If by(8 + 8 * (i - 1)) = "1" Then b(i) = b(i) Or "1" Else b(i) = b(i) And &HFE End If byte2bit = byte2bit & Chr$(b(i))

Next i
End Function
Private Function bit2byte(s As String) As String
Dim s2 As String
Dim x As String
Dim i As Integer, k As Integer
Dim ilen As Integer

ilen = Len(s)
Dim b()
Dim s1()
ReDim s1(ilen)
ReDim b(ilen * 8)
s2 = ""
For i = 1 To ilen
x = Mid\$(s, i, 1)
s1(i) = Asc(x)

If s1(i) And &H80 Then
b(1 + 8 * (i - 1)) = 1
Else
b(1 + 8 * (i - 1)) = 0
End If

If s1(i) And &H40 Then
b(2 + 8 * (i - 1)) = 1
Else
b(2 + 8 * (i - 1)) = 0
End If

If s1(i) And &H20 Then
b(3 + 8 * (i - 1)) = 1
Else
b(3 + 8 * (i - 1)) = 0
End If

If s1(i) And &H10 Then
b(4 + 8 * (i - 1)) = 1
Else
b(4 + 8 * (i - 1)) = 0
End If

If s1(i) And &H8 Then
b(5 + 8 * (i - 1)) = 1
Else
b(5 + 8 * (i - 1)) = 0
End If

If s1(i) And &H4 Then
b(6 + 8 * (i - 1)) = 1
Else
b(6 + 8 * (i - 1)) = 0
End If

If s1(i) And &H2 Then
b(7 + 8 * (i - 1)) = 1
Else
b(7 + 8 * (i - 1)) = 0
End If

If s1(i) And "1" Then
b(8 + 8 * (i - 1)) = 1
Else
b(8 + 8 * (i - 1)) = 0
End If

Next i

For k = 1 To ilen * 8
s2 = s2 & b(k)
If k Mod 8 = 0 Then
s2 = s2
End If
Next k
bit2byte = s2
End Function

Private Sub Command1_Click()
Dim s As String
Dim s2 As String
s = Text1.Text
s2 = bit2byte(s)
Text2.Text = s2
End Sub

Private Sub Command2_Click()
Dim s As String
Dim s1 As String
s = Text2.Text
s1 = byte2bit(s)
Text2.Text = s1
End Sub

0 0