简体   繁体   中英

Byte array to int16 array

Is there a more efficient way to convert byte array to int16 array ?? or is there a way to use Buffer.BlockCopy to copy evry two byte to int16 array ???

public static int[] BYTarrToINT16arr(string fileName)
{
try
{
int bYte = 2;
byte[] buf = File.ReadAllBytes(fileName); 
int bufPos = 0;
int[] data = new int[buf.Length/2];
byte[] bt = new byte[bYte];
for (int i = 0; i < buf.Length/2; i++)
{
Array.Copy(buf, bufPos, bt, 0, bYte);
bufPos += bYte;
Array.Reverse(bt);
data[i] = BitConverter.ToInt16(bt, 0);
}
return data;
}
catch
{
return null;
}
}   

Use a FileStream and a BinaryReader . Something like this:

var int16List = List<Int16>();
using (var stream = new FileStream(filename, FileMode.Open))
using (var reader = new BinaryReader(stream))
{
    try
    {
        while (true)
            int16List.Add(reader.ReadInt16());
    }
    catch (EndOfStreamException ex)
    {
        // We've read the whole file
    }
}
return int16List.ToArray();

You can also read the whole file into a byte[] , and then use a MemoryStream instead of the FileStream if you want.

If you do this then you'll also be able to size the List approrpriately up front and make it a bit more efficient.

This works if you don't mind using interopservices. I assume it is faster than the other techniques.

using System.Runtime.InteropServices;   

public Int16[] Copy_Byte_Buffer_To_Int16_Buffer(byte[] buffer)

{
    Int16[] result = new Int16[1];
    int size = buffer.Length;
    if ((size % 2) != 0)
    {
        /* Error here */
        return result;
    }
    else
    {
        result = new Int16[size/2];
        IntPtr ptr_src = Marshal.AllocHGlobal (size);
        Marshal.Copy (buffer, 0, ptr_src, size);
        Marshal.Copy (ptr_src, result, 0, result.Length);
        Marshal.FreeHGlobal (ptr_src);
        return result;
    }
}

Apart from having an off-by-one possibility in case the number of bytes is odd (you'll miss the last byte) your code is OK. You can optimize it by dropping the bt array altogether, swapping i*2 and i*2+1 bytes before calling BitConverter.ToInt16 , and passing i*2 as the starting index to the BitConverter.ToInt16 method.

try...

int index = 0;            
var my16s = bytes.GroupBy(x => (index++) / 2)
           .Select(x => BitConverter.ToInt16(x.Reverse().ToArray(),0)).ToList();
var bytes = File.ReadAllBytes(path);

var ints = bytes.TakeWhile((b, i) => i % 2 == 0).Select((b, i) => BitConverter.ToInt16(bytes, i));

if (bytes.Length % 2 == 1)
{
    ints = ints.Union(new[] {BitConverter.ToInt16(new byte[] {bytes[bytes.Length - 1], 0}, 0)});
}

return ints.ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM