两种方法 位运算 和 纯粹字符串处理
Private Sub Command1_Click()
'EnCode1 位运算实现加密
Dim arr() As Byte
Dim i As Integer
arr = StrConv(Text1.Text, vbFromUnicode)
For i = 0 To UBound(arr)
EnCode1 arr(i)
Next
Text2.Text = StrConv(arr, vbUnicode)
End Sub
Sub EnCode1(x As Byte) 'vb 默认byref 传地址
Dim h As Byte
Dim l As Byte
h = x And &HF0 'x字节高四位放入变量h, h低四位置零
x = Not x 'x按位取反
x = x And &HF '高四位置零,保留取反后的低四位
x = x * &H2 '乘2左移1位 (第0~第6位移到第1~第7位,最高位丢弃)
l = x And &H10 '取出第4位
x = x And &HF 'x高四位置零
l = l / &HF '第4位移到第0位
x = x Or l '第四位拼到x上完成低4位的移位
x = x Or h '高低4位拼在一起,byref形参返回
End Sub
'----------------------------------------------------------
Private Sub Command2_Click()
'EnCode2 纯字符串处理实现
Dim s As String
Dim n As Integer
Dim i As Integer
s = ""
n = Len(Text1.Text)
For i = 1 To n
s = s & EnCode2(Mid(Text1.Text, i, 1))
Next
Text3.Text = s
End Sub
Function EnCode2(x As String) As String
Dim a As Integer
Dim s As String
a = Asc(x)
s = dec2binstr(a)
Dim sarr(1 To 9) As String
Dim i As Integer
For i = 1 To 8
sarr(i) = Mid(s, i, 1)
Next
For i = 5 To 8
If sarr(i) = "1" Then
sarr(i) = "0"
Else
sarr(i) = "1"
End If
Next
sarr(9) = sarr(4)
For i = 5 To 8
sarr(i - 1) = sarr(i)
Next
sarr(8) = sarr(4)
sarr(4) = sarr(9)
s = ""
For i = 1 To 8
s = s & sarr(i)
Next
a = binstr2dec(s)
EnCode2 = Chr(a)
End Function
Function dec2binstr(d As Integer) As String
Dim s As String
Dim a As Integer
Dim b As Integer
a = d
s = ""
Do
b = a Mod 2
a = a \ 2
If b > 0 Then
s = "1" & s
Else
s = "0" & s
End If
Loop While a >= 1
a = Len(s)
If a < 8 Then
s = String(8 - a, "0") & s
End If
dec2binstr = s
End Function
Function binstr2dec(s As String) As Integer
Dim x As Integer
x = &H0
For i = 1 To 8
x = x * &H2 + AscB(Mid(s, i, 1)) - AscB("0")
Next
binstr2dec = x
End Function
追问能简单点吗
我这里有题目,但是做出来之后我用VB运行不能得到正确结果
能帮我看看吗?
太复杂了