字节数组到int16数组

本文关键字:数组 int16 字节 字节数 | 更新日期: 2023-09-27 18:28:54

是否有更有效的方法将字节数组转换为int16数组??或者有没有一种方法可以使用Buffer.BlockCopy将每两个字节复制到int16数组???

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;
}
}   

字节数组到int16数组

使用FileStreamBinaryReader。类似这样的东西:

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();

您也可以将整个文件读取到byte[]中,然后根据需要使用MemoryStream而不是FileStream

如果你这样做,那么你也可以适当地调整List的大小,并使其更有效率。

除了在字节数为奇数(您会错过最后一个字节)的情况下有一个off-by-one的可能性外,您的代码还可以。您可以通过完全删除bt数组、在调用BitConverter.ToInt16之前交换i*2i*2+1字节,并将i*2作为BitConverter.ToInt16方法的起始索引来优化它。

如果您不介意使用互操作服务,这是有效的。我认为它比其他技术更快。

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;
    }
}
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();

尝试。。。

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