Search code examples
arraysexcelvbabytejpeg

Why does byte writing to a file from VBA add 1100 to each byte?


I am trying to copy an image as a byte array to a file in vba.

The first three bytes of the file, represented as a byte array:

   Dim arr(3) As Byte arr = {23,21,2f}

The code that copies from an array to a new file is:

Open "try444.jpg" For Binary As #1

For cnt = 1 To UBound(arr)

    Put #1, LOF(1) + 1, arr(cnt)

Next

but it writes 1100 2311 0023 1100 2111 002f 1100 to the file (all in hex)

What is wrong with my code?


Solution

  • because arr is being redefined somewhere. If I write the procedure as a single function:

    Option Explicit
    Sub test()
    Dim cnt As Long
    Dim arr(3) As Byte
    
    arr(1) = &H23
    arr(2) = &H21
    arr(3) = &H2F
    
    Open "try444.jpg" For Binary As #1
    
    For cnt = 1 To UBound(arr)
    
        Put #1, LOF(1) + 1, arr(cnt)
    
    Next
    Close #1
    
    End Sub
    

    then I get exactly the bytes you would expect 23 21 2F

    If I neglect to define the type (or I don't have Option Explicit) then it becomes a variant, and then it's anyone's guess as to what will appear, as the variant datatype includes a type code. (in my case, I get 02 00 23 00 02 00 21 00 02 00 2f 00)