开发者

Converting array of bytes to array of shorts without copying data

I have an开发者_运维问答 array of bytes that are actually 16-bit samples from a sound card. So 1000 bytes actually represents 500 Short (16-bit values).

Currently I'm converting them like this:

byte [] inputData = new byte[1000];
short [] convertedData = new short[500];
Buffer.BlockCopy(inputData, 0, convertedData , 0, 1000);

It works fine and it's pretty quick as it's a low-level byte copy.

However is there a way to do it without the copy? i.e. tell C# to treat this area of memory as an array of 500 shorts instead of 1000 bytes? I know that in C/C++ I could just cast the pointer and it would work.

This copy happens in a tight loop, up to 5000 times a second, so if I can remove the copy it would be worthwhile.


StructLayout lets you control the physical layout of the data fields in a class or structure. It is typically used when interfacing with unmanaged code which expects the data in a specific layout.

Give this a try:

[StructLayout(LayoutKind.Explicit)]
struct UnionArray
{
    [FieldOffset(0)]
    public Byte[] Bytes;

    [FieldOffset(0)]
    public short[] Shorts;
}

static void Main(string[] args)
{
    var union = new UnionArray() {Bytes = new byte[1024]};

    foreach (short s in union.Shorts)
    {
        Console.WriteLine(s);
    }
}


Perhaps a C# analog of the C-language union would do the trick.


bytes[] inputData = Array.ConvertAll<short, bytes>(bytes, delegate(short[] convertedData) { return short.Parse(convertedData); } );

something like that, i didnt check, but maybe that'll help you out :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜