Introduction to defining byte array in vbs

Time:2022-5-17

At nightQQA friend with a nickname of “random code” answered a question in soso:

stayVBSThere are ways to definebytearrayAre you?
Is there any way to define byte array in VBS? It’s a byte subtype array (vartype is 8209). Note that it’s not VB!

But the answer was really ugly. I didn’t even understand what others asked, and the man was actually satisfied. I don’t know what he was thinking.

It’s all right if you’re free. I’ll give you a brief answer. First of all, we should find out what others are asking. VBS is a weakly typed scripting language. There is only one data type, called variant, but variant can be further divided into several sub types. It will not be expanded here. For details《VBScript data type》。 The so-called byte subtype array (vartype is 8209), that is, the subtype isByteArray of (vbbyte + vbarray = 17 + 8192 = 8209).

For example, msxml2 The ResponseBody property of xmlhttp object returns the byte array:

Copy codeThe codes are as follows:


‘Author: Demon
‘Website: http://demon.tw
‘Date: 2012/2/22
Dim http, res
Set http = CreateObject(“Msxml2.XMLHTTP”)
http.open “GET”, “http://demon.tw”, False
http.send
res = http.responseBody
WScript.Echo VarType(res), TypeName(res)


Another example is ADODB The read method of the stream object also returns a byte array:

Copy codeThe codes are as follows:


‘Author: Demon
‘Website: http://demon.tw
‘Date: 2012/2/22
Dim ado, data
Set ado = CreateObject(“ADODB.Stream”)
ado.Type = 1
ado.Open
ado.LoadFromFile “demon.tw”
data = ado.Read
WScript.Echo VarType(data), TypeName(data)


So how to define a byte array in VBS? Some people say that it’s not easy. Just use the cbyte function to force the conversion? Really? Write a simple example to test:

Copy codeThe codes are as follows:


‘Author: Demon
‘Website: http://demon.tw
‘Date: 2012/2/22
Dim a(9), i
For i = 0 To 9
a(i) = CByte(i)
Next
WScript.Echo VarType(a), TypeName(a)


‘the output 8204 variant() program outputs 8204 variant(). Unfortunately, this is not what we want.

So what is the right way? In fact《Another method of reading and writing binary files with vbs》It appears in, using msxml2 Domdocument object:

Copy codeThe codes are as follows:


‘Author: Demon
‘Website: http://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. The hexadecimal value of TW is
’64 65 6D 6F 6E 2E 74 77
node.Text = “64656D6F6E2E7477”
bytes = node.NodeTypedValue
WScript.Echo VarType(bytes), TypeName(bytes)


In this way, the bytes variable is a byte array. If you know other methods, you are welcome to comment.

Original text: http://demon.tw/programming/vbs-byte-array.html