1

我想手动创建一个二进制脚本,然后将其保存为二进制文件。

我想附加以下所有字节并从中创建一个二进制文件。

&HF0
&HF1
&HF2

我希望能够做这样的事情:

Dim generateData(3) As Byte
generateData(0) = &HFF
generateData(1) = &HFE
generateData(2) = &HFC

但显然As Byte不适用于 Vbscript。我确实使用以下函数将二进制数组写入磁盘(至少当我能够创建二进制数组时)

Function SaveBinaryData(FileName, ByteArray)
  Const adTypeBinary = 1
  Const adSaveCreateOverWrite = 2

  'Create Stream object
  Dim BinaryStream
  Set BinaryStream = CreateObject("ADODB.Stream")

  'Specify stream type - we want To save binary data.
  BinaryStream.Type = adTypeBinary

  'Open the stream And write binary data To the object
  BinaryStream.Open
  BinaryStream.Write ByteArray

  'Save binary data To disk
  BinaryStream.SaveToFile FileName, adSaveCreateOverWrite
End Function
4

2 回答 2

2

使用 TypeText-ADODB.Stream 写入文件并将其作为 TypeBinary-ADODB.Stream 读回是一种常见的解决方案,但它需要一个临时文件和文本安全字节。使用System.IO.MemoryStream有更好的方法

'Dim generateData(3) As Byte
Dim generateData(3) 
generateData(0) = &HFF
generateData(1) = &HFE
generateData(2) = &HFC

Set mem = CreateObject("System.IO.MemoryStream")
mem.SetLength(0)
For Each B in generateData 
   mem.WriteByte (B)
Next
generateData_as_ByteArray = mem.ToArray()  'Returns a VB Style, "Byte()"   [Byte Array]

或者在问题的原始示例中

Function SaveBinaryData(FileName, VbByteArray)
  Const adTypeBinary = 1
  Const adSaveCreateOverWrite = 2

  'Create Stream object
  Dim BinaryStream
  Set BinaryStream = CreateObject("ADODB.Stream")

  'Specify stream type - we want To save binary data.
  BinaryStream.Type = adTypeBinary

  'Open the stream And write binary data To the object
  BinaryStream.Open

  'Covert VBS Array of Byte Values; TypeName "Variant()"
  'to a true Byte Array; TypeName "Byte()"
  Set mem = CreateObject("System.IO.MemoryStream")
  mem.SetLength(0)
  For Each B in VbByteArray
     mem.WriteByte (B)
  Next
  ByteArray = mem.ToArray() 'Output as Btye()

  'Works
  BinaryStream.Write ByteArray

  'Save binary data To disk
  BinaryStream.SaveToFile FileName, adSaveCreateOverWrite
End Function

ADODB.Stream (在二进制模式)只允许您添加字节数组,但密切相关的System.IO.MemoryStream也允许您将数据添加为字节数组,但是具有.WriteByte函数,它只需要一个字节,它VBS可以做到。

System.IO.MemoryStream.ToArray返回一个 ByteArray 与.readADODB.Stream的作用相同;两者都是ADODB.Stream .Write想要的类型“byte()”。

于 2020-10-30T22:13:51.240 回答
1

我已经看到使用这些方面的一些东西:

Sub WriteBinary(FileName, Buf)  

    Dim I, aBuf, Size, bStream  

    Size = UBound(Buf): ReDim aBuf(Size \ 2)  

    For I = 0 To Size - 1 Step 2  

        aBuf(I \ 2) = ChrW(Buf(I + 1) * 256 + Buf(I))  

    Next  

    If I = Size Then aBuf(I \ 2) = ChrW(Buf(I))  

    aBuf=Join(aBuf, "")  

    Set bStream = CreateObject("ADODB.Stream")  

    bStream.Type = 1: bStream.Open  

    With CreateObject("ADODB.Stream")  

        .Type = 2 : .Open: .WriteText aBuf  

        .Position = 2: .CopyTo bStream: .Close  

    End With  

    bStream.SaveToFile FileName, 2: bStream.Close  

    Set bStream = Nothing  

End Sub
于 2009-02-13T23:42:39.813 回答