写十六进制字符串二进制模式文件(Write hex-string to file in binary

2019-11-05 11:31发布

我想写的十六进制值二进制文件,以便它们看起来是一样的,当我在十六进制编辑器打开。

我当前的代码是这样的:

Sub Write2Binary()
Dim i As Integer
Dim nFileNum As Integer
Dim sFilename As String

sFilename = "D:\OutputPath\Test.bin"

strBytes = "F3 A1 02 00 04 00 8D 24 44 C3 8C 03 83 49 26 92 B5"
arrBytes = Split(strBytes)

nFileNum = FreeFile

Open sFilename For Binary Lock Read Write As #nFileNum

For i = LBound(arrBytes) To UBound(arrBytes)
    Put #nFileNum, , arrBytes(i)
Next i

Close #nFileNum

End Sub

此代码将产生以下二进制文件,当我在十六进制编辑器打开它看起来是这样的:

08 00 02 00 46 33 08 00 02 00 41 31 08 00 02 00 
30 32 08 00 02 00 30 30 08 00 02 00 30 34 08 00 
02 00 30 30 08 00 02 00 38 44 08 00 02 00 32 34 
08 00 02 00 34 34 08 00 02 00 43 33 08 00 02 00 
38 43 08 00 02 00 30 33 08 00 02 00 38 33 08 00 
02 00 34 39 08 00 02 00 32 36 08 00 02 00 39 32 
08 00 02 00 42 35 

这是我想在二进制文件的内容不同。 当我打开十六进制编辑器文件我喜欢看到以下内容:

F3 A1 02 00 04 00 8D 24 44 C3 8C 03 83 49 26 92 B5

我怎样才能做到这一点?

Answer 1:

数据代表字节的十六进制值进行wriiten二进制文件。 Split产生一个字符串数组,每一个元素是一个十六进制值的字符串表示形式。 作为共产国际告诉你,你需要将它们转换为数字。

Put使用的类型Varname参数来确定的长度(字节数)来写,所以在这种情况下,你需要转换为Byte ,所以使用CByte来转化。 CByte还需要知道的值是十六进制,所以用在前面加上&H

所有了,你的代码变得

Sub Write2Binary()
    Dim i As Long
    Dim nFileNum As Integer
    Dim sFilename As String
    Dim strBytes As String
    Dim arrBytes As Variant

    sFilename = "D:\OutputPath\Test.bin"

    strBytes = "F3 A1 02 00 04 00 8D 24 44 C3 8C 03 83 49 26 92 B5"
    arrBytes = Split(strBytes)

    nFileNum = FreeFile

    Open sFilename For Binary Lock Read Write As #nFileNum

    For i = LBound(arrBytes) To UBound(arrBytes)
        Put #nFileNum, , CByte("&H" & arrBytes(i))
    Next i

    Close #nFileNum
End Sub


文章来源: Write hex-string to file in binary mode