VBS字节数组Byte()的处理方法

标签: , , ,

在VBS中定义字节数组Byte()》一文中介绍了在 VBS 中定义字节数组的方法,本文介绍一下字节数组Byte()的处理方法。

'Author: Demon
'Website: https://demon.tw
'Date: 2012/2/22
Dim xmldoc, node, bytes
Set xmldoc = CreateObject("Msxml2.DOMDocument")
Set node = xmldoc.CreateElement("binary")
node.DataType = "bin.hex"
'demon.tw 的十六进制值为
'64 65 6D 6F 6E 2E 74 77
node.Text = "64656D6F6E2E7477"
bytes = node.NodeTypedValue
WScript.Echo VarType(bytes), TypeName(bytes)

这是昨天的代码,定义了一个内容为 demon.tw 的字节数组,VarType 函数返回8209(vbByte + vbArray),TypeName 函数返回 Byte()。

没错,我们是定义了一个字节数组Byte(),但是我们要怎样访问单个数组元素呢?你说那还不简单,直接用下标不就行了:

'Author: Demon
'Website: https://demon.tw
'Date: 2012/2/23
Dim xmldoc, node, bytes, t
Set xmldoc = CreateObject("Msxml2.DOMDocument")
Set node = xmldoc.CreateElement("binary")
node.DataType = "bin.hex"
'demon.tw 的十六进制值为
'64 65 6D 6F 6E 2E 74 77
node.Text = "64656D6F6E2E7477"
bytes = node.NodeTypedValue
WScript.Echo VarType(bytes), TypeName(bytes)
t = bytes(0)
'Microsoft VBScript runtime error (13, 1) : Type mismatch

哦,居然报错了。实际上,VBScript 并不知道怎样处理一个字节数组Byte(),它知道怎样处理 Byte 和 Array(),但是两者结合起来就不懂了。

秘密在于,字节数组Byte()事实上只是字节字符串,所以可以用字符串函数来处理:

'Author: Demon
'Website: https://demon.tw
'Date: 2012/2/23
Dim xmldoc, node, bytes, t
Set xmldoc = CreateObject("Msxml2.DOMDocument")
Set node = xmldoc.CreateElement("binary")
node.DataType = "bin.hex"
'demon.tw 的十六进制值为
'64 65 6D 6F 6E 2E 74 77
node.Text = "64656D6F6E2E7477"
bytes = node.NodeTypedValue
WScript.Echo VarType(bytes), TypeName(bytes)
t = MidB(bytes, 1, 1) 'MidB, not Mid
WScript.Echo t, VarType(t), TypeName(t), Len(t), LenB(t)

那么如何遍历数组元素呢?聪明的你一定能很快想出来:

'Author: Demon
'Website: https://demon.tw
'Date: 2012/2/23
Dim xmldoc, node, bytes, i, t
Set xmldoc = CreateObject("Msxml2.DOMDocument")
Set node = xmldoc.CreateElement("binary")
node.DataType = "bin.hex"
'demon.tw 的十六进制值为
'64 65 6D 6F 6E 2E 74 77
node.Text = "64656D6F6E2E7477"
bytes = node.NodeTypedValue
WScript.Echo VarType(bytes), TypeName(bytes)
For i = 1 To LenB(bytes)
    t = MidB(bytes, i, 1)
    WScript.Echo t, VarType(t), TypeName(t), Len(t), LenB(t)
Next
赞赏

微信赞赏支付宝赞赏

随机文章:

  1. WMI中的Win32_PingStatus类
  2. 中兴F460 V5.0光猫查看超级管理员密码
  3. 文件夹拒绝访问且文件夹显示为空的解决方法
  4. VBS文件编码与Unicode
  5. VBS普通青年 vs 文艺青年 vs 2B青年

一条评论 发表在“VBS字节数组Byte()的处理方法”上

  1. qiuqiu说道:

    Const SSFMOpenForRead = 0

    Dim Stream
    Set Stream = CreateObject(“SAPI.spFileStream”)
    Stream.Open “E:\test\China.txt”,SSFMOpenForRead
    Stream.Read Buffer,1024

    vartype(Buffer) = 8209
    typename(Buffer) = Byte()

    俄国网站看到的,据说比ADODB.Stream处理二进制文件的效率高。

留下回复