vb里数组与字符串之间相互转化

2024-11-24 01:15:34
推荐回答(2个)
回答1:

Sub BinToStr()
Dim b As Byte
Dim k As Integer
Dim k1 As Integer
Dim k2 As Integer
Dim onestr As String
Dim s As String
Open "c:\1.jpg" For Binary As #1
i = 1
While Not EOF(1)
Get #1, i, b
k = Asc(b)
k1 = k \ 16
k2 = k Mod 16
s = s & IntToHexStr(k1) & IntToHexStr(k2)
i = i + 1
Wend
Close #1

End Sub
Sub StrToBin()
Dim b As Byte
Dim k As Integer
Dim k1 As String
Dim k2 As String
Dim onestr As String
Dim s As String
Open "c:\1.jpg" For Binary As #1
i = 1
While CStr(s) > 0
k1 = Left(s, 1)
k2 = Mid(s, 2, 1)
s = Mid(s, 3)

k = HexStrToInt(k1) * 16 + HexStrToInt(k2)
b = Chr(k)
Put #1, i, b
i = i + 1
Wend
Close #1

End Sub

Function IntToHexStr(a As Integer) As String
Select Case k
Case 10:
IntToHexStr = "A"
Case 11:
IntToHexStr = "B"
Case 12:
IntToHexStr = "C"
Case 13:
IntToHexStr = "D"
Case 14:
IntToHexStr = "E"
Case 15:
IntToHexStr = "F"
Case Else:
IntToHexStr = CStr(a)
End Select
End Function

Function HexStrToInt(a As String) As Integer
Select Case a
Case "A":
HexStrToInt = 10
Case "B":
HexStrToInt = 11
Case "C":
HexStrToInt = 12
Case "D":
HexStrToInt = 13
Case "E":
HexStrToInt = 14
Case "F":
HexStrToInt = 15
Case Else:
HexStrToInt = CInt(a)
End Select

End Function

没有VB的环境,也N年没用过VB了,不知道有没有错误,你稍微调试一下就应该可以,原理就是用ASC码来表示二进制数

回答2:

二进制数组变成字符串一定会带来长度的增加,这个你可以接受吗?比如1K字节的二进制文件,uuencoder下来大约1.5K,Base 64下来大概1.3K,最简单的ASC方式大约2K,你能接受吗?