以二进制模式将十六进制字符串写入文件 [英] Write hex-string to file in binary mode
问题描述
我想将十六进制值写入二进制文件,以使它们在十六进制编辑器中打开时看起来相同.
I want to write the hexadecimal values to a binary file in order they look the same when I open in hex editor.
我当前的代码是这样:
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
此代码生成以下二进制文件,当我在十六进制编辑器中打开它时,它看起来像这样:
This code produces the following binary file that when I open it in a Hex editor looks like this:
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
这与我要在二进制文件中拥有的内容不同.当我在十六进制编辑器中打开文件时,我喜欢看到以下内容:
That is different to the content I want to have in binary file. When I open the file in Hex editor I like to see the following content:
F3 A1 02 00 04 00 8D 24 44 C3 8C 03 83 49 26 92 B5
我该怎么做?
推荐答案
您的数据表示要写入二进制文件的字节的十六进制值. Split
生成一个字符串数组,每个元素都是一个十六进制值的字符串表示形式.正如Comintern告诉您的那样,您需要将它们转换为数字.
Your data represents Hex values of bytes to be wriiten to a binary file. Split
produces an array of strings, each element being a string represention of a hex value. As Comintern told you, you need to convert them to numbers.
Put
使用Varname
参数的类型来确定要写入的长度(字节数),因此在这种情况下,您需要转换为Byte
,因此请使用CByte
进行转换. CByte
还需要知道值是十六进制,所以请以&H
Put
uses the type of the Varname
parameter to determine the length (number of bytes) to write, so in this case you need to convert to Byte
, so use CByte
to convert. CByte
also needs to know the values are Hex, so prepend with &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
这篇关于以二进制模式将十六进制字符串写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!