VBS中轉換二進制數據為字符串常用辦法
2019-10-26 17:57:59
供稿:網友
至少有三種以上辦法,可以把二進制數據(比如您從ASP的Request.BinaryRead方法得到的數據)轉換為字符串。
第一種:使用VBS的MultiByte 方法
實例:
Function SimpleBinaryToString(Binary)
'SimpleBinaryToString converts binary data (VT_UI1 | VT_ARRAY Or MultiByte string)
'to a string (BSTR) using MultiByte VBS functions
Dim I, S
For I = 1 To LenB(Binary)
S = S & Chr(AscB(MidB(Binary, I, 1)))
Next
SimpleBinaryToString = S
End Function
這個方法非常簡單明了,但是處理大數據流時,比較慢。
建議只用來處理100KB以下的數據。
下面的這個類似的方法,性能稍微好些:
Function BinaryToString(Binary)
'Antonin Foller, http://www.pstruh.cz
'Optimized version of a simple BinaryToString algorithm.
Dim cl1, cl2, cl3, pl1, pl2, pl3
Dim L
cl1 = 1
cl2 = 1
cl3 = 1
L = LenB(Binary)
Do While cl1<=L
pl3 = pl3 & Chr(AscB(MidB(Binary,cl1,1)))
cl1 = cl1 + 1
cl3 = cl3 + 1
If cl3>300 Then
pl2 = pl2 & pl3
pl3 = ""
cl3 = 1
cl2 = cl2 + 1
If cl2>200 Then
pl1 = pl1 & pl2
pl2 = ""
cl2 = 1
End If
End If
Loop
BinaryToString = pl1 & pl2 & pl3
End Function
BinaryToString方法比SimpleBinaryToString方法性能高20倍。建議用來處理2MB以下的數據。
第二種方法:使用ADODB.Recordset
ADODB.Recordset 可以讓你支持幾乎所有VARIANT支持的數據類型,你可以用它在string和
binary之間轉換。
Function RSBinaryToString(xBinary)
'Antonin Foller, http://www.pstruh.cz
'RSBinaryToString converts binary data (VT_UI1 | VT_ARRAY Or MultiByte string)
'to a string (BSTR) using ADO recordset
Dim Binary
'MultiByte data must be converted To VT_UI1 | VT_ARRAY first.
If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary
Dim RS, LBinary
Const adLongVarChar = 201