0

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?

3
  • 2
    You mean like this? Commented Feb 12, 2019 at 21:43
  • I'm not sure if that link answers my question Commented Feb 12, 2019 at 23:32
  • 1
    You're outputting 4 bytes of String for each value (2 per character). You just need to convert them to numbers from hex strings. That link answers the question of how to do that. Commented Feb 12, 2019 at 23:36

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.