Post

Convert System.Array containing Int16 values to an Byte array?

There’s got to be an easier way to do this. FileStream only allows you to use a Byte array when reading/writing. I’ve got a COM object that gives me an array of Int16 values formatted as a System.Array. I need to convert this to an array of bytes. Using the BitConverter class doesn’t help, unless I want to iterate through every Int16 item in the array and copy the resulting array of bytes into another largest byte array representing the complete data. So, here’s the answer I came up with, though I’m thinking there’s got to be a better way.

1
2
3
4
5
6
7
8
Dim pcmBuffer As Array
Dim bytes() As Byte
Dim handle As GCHandle = GCHandle.Alloc(pcmBuffer, GCHandleType.Pinned)
Dim ptr As IntPtr = handle.AddrOfPinnedObject()
ReDim bytes(pcmBuffer.Length * 2)
Marshal.Copy(ptr, bytes, 0, bytes.Length)
handle.Free()
fs.Write(bytes, 0, bytes.Length)

What I don’t have a solution for, even a halfway good one, is for converting the byte array back to an array of Int16’s when reading from the file and passing back to the COM component. My only guess on this problem is to use the BitConverter class and iterate through all of the values to create the resulting System.Array. Yuk!

From a different perspective, using this method seems very similar to using the memcpy.

This post is licensed under CC BY 4.0 by the author.