【问题标题】:What is the best way to write a Longs array into a HEX file in VBA?在 VBA 中将 Longs 数组写入 HEX 文件的最佳方法是什么?
【发布时间】:2020-09-26 19:16:07
【问题描述】:

我有一个 Longs 数组(在 10k 或可能 100k 长的范围内),我必须将它们作为 8 位 little-endians 放入 HEX 文件 (.wav) 中。做这个的最好方式是什么?

我使用了一个简单的 PUT,但它没有按计划进行。我尝试了一些应该产生的测试值

DE A8 抄送 16 00 00 1E 5B

我得到了代替

DE A8 FF FF CC 16 00 00 00 00 00 00 1E 5B 00 00

我使用的代码如下。你知道发生了什么以及如何解决这个问题吗?在我尝试的每个值中,记录之间总是有一个额外的 00 00 或 FF FF。

Sub Gera_sinal()
Dim sinal() As Long

ReDim sinal(3)

'Test values
 sinal(0) = -22306
 sinal(1) = 5836
 sinal(2) = 0
 sinal(3) = 23326

'Creates a file and puts the values in it
Dim n_arq As Integer
Dim path As String

path = "C:\Users\DELL\Desktop\App\WAVs\Sinal_VBA.wav"

     Set fs = CreateObject("Scripting.FileSystemObject")
     Set a = fs.CreateTextFile(path, True)
     a.Close

     n_arq = FreeFile
     Open path For Binary As n_arq

     Put n_arq, , sinal
    Close n_arq

End sub

【问题讨论】:

    标签: arrays vba file hex write


    【解决方案1】:

    数据类型 Long 的存储大小为 4 个字节。因此,由于您已将数组声明为 Long,因此数组中的每个值都将作为 4 个字节存储在文件中。

    因此,例如,如您所知,-22,306 转换为十六进制的 A8 DE。但是,由于该值将存储为 4 个字节,因此文件中存储的实际值将是 FF FF A8 DE,或小端的 DE A8 FF FF。

    现在,如果值的范围在 -32,768 和 32,767 之间(含),您可以将数组声明为 Integer。这意味着每个值将作为 2 个字节存储在文件中。所以 -22,306 将被存储为 DE A8。

    顺便说一句,您可以避免使用 FileSystemObject 对象来将现有文件截断为 0 字节。相反,您可以使用 Kill 方法删除已存在的文件,因为二进制模式下的 Open 语句会在文件不存在时创建它。

    因此,您的宏可以重写如下...

    Sub Gera_sinal()
    
        Dim sinal() As Integer
    
        ReDim sinal(3)
    
        'Test values
        sinal(0) = -22306
        sinal(1) = 5836
        sinal(2) = 0
        sinal(3) = 23326
    
        'Creates a file and puts the values in it
        Dim n_arq As Integer
        Dim path As String
    
        path = "C:\Users\DELL\Desktop\App\WAVs\Sinal_VBA.wav"
    
        'delete file, if it already exists
        On Error Resume Next
        Kill path
        On Error GoTo 0
    
        n_arq = FreeFile
        Open path For Binary Access Write As n_arq
            Put n_arq, , sinal
        Close n_arq
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 2011-06-15
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多