Search code examples
excelvbabinaryfiles

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.

My current code is this:

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

How can I do this?


Solution

  • 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 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

    All up, your code becomes

    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