字串與二進位制互相轉化(不包含漢字) (轉)

amyz發表於2007-08-16
字串與二進位制互相轉化(不包含漢字) (轉)[@more@]

對於二進位制與字元的互換,是由於我要做DES的需要才設計的
現在把我的源程式釋出:

先建立一個工程
在上畫
兩個textbox,命名為text1,text2
兩個commanutton, 命名為command1,command1
其他定義自己去該吧!

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


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752019/viewspace-962598/,如需轉載,請註明出處,否則將追究法律責任。

相關文章