【问题标题】:BitConverter.ToInt16 giving "Destination array is not long enough"BitConverter.ToInt16 给出“目标数组不够长”
【发布时间】:2017-06-20 00:43:47
【问题描述】:

我正在尝试将字节数组转换为这样的短裤数组:

Public Sub mixFinal()
    Dim patch1Buffer(patch1.Length - 44) As Byte

    System.Array.Copy(patch1, 44, patch1Buffer, 0, patch1.Length - 44)

    Dim patch1ShortBuffer(patch1Buffer.Length) As Short

    For x = 0 To patch1Buffer.Length - 1 Step 1
        patch1ShortBuffer(x) = System.BitConverter.ToInt16(patch1Buffer, x)
    Next
End Sub

'patch1' 是一个字节数组,它是通过使用 IO.File.ReadAllBytes 方法读取 .wav 文件而创建的。

编译程序时Visual Studio给我这个错误:

Destination array is not long enough to copy all the items in the collection. Check array index and length.

我尝试将 'patch1Buffer' 和 'patch1ShortBuffer' 的大小更改为更高的值,但仍然给出错误...代码有什么问题?

【问题讨论】:

    标签: arrays vb.net byte type-conversion


    【解决方案1】:

    bytes 中的 short 大小等于 2 bytes

    因此,转换字节数组时产生的短路次数减少了两倍。

    以下代码会将您的字节数组转换为短裤:

    Imports System.Runtime.InteropServices ' for alternative
    
    Module Module1
    
        Sub Main()
            Dim bytes(1024-1) As Byte
    
            Dim shortSize = 2 ' alternative: shortCount = Marshal.SizeOf(GetType(Short))
            Dim shortCount = bytes.Length / shortSize
    
            Dim shorts(shortCount) as Short
            For i = 0 To shortCount-1
               shorts(i)= BitConverter.ToInt16(bytes, i*shortSize)
            Next
    
        End Sub
    
    End Module
    

    【讨论】:

      【解决方案2】:

      好的,所以我在这里假设您正在尝试将单个字节转换为短裤......在这种情况下,bitconvertor.toint16 函数将在 patch1buffer 的末尾运行,因为它一次检索 2 个字节。

      使用

      patch1ShortBuffer(x) = cShrt(patch1Buffer(x))
      

      改为。

      如果您尝试将这些对作为 uShort 抓取,则需要为 patch1ShortBuffer 的一半大小,使用 x*2 迭代到它的长度以进行 ToInt16 调用

      【讨论】:

        猜你喜欢
        • 2012-05-08
        • 2012-08-02
        • 1970-01-01
        • 2020-09-21
        • 2014-05-11
        • 2016-04-08
        • 2022-01-23
        • 1970-01-01
        • 2019-09-12
        相关资源
        最近更新 更多