Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Convert byte[] to short[]

2.50/5 (4 votes)
2 Aug 2024CPOL 4.1K  
Converting byte[] to short[]. Can be used when dealing with raw audio samples.
I came across an old question, some people on here get a little butt hurt when you post on an old question, so I decided to post a tip/trick on how, in case someone is searching for the same.
C#
static unsafe short[] ToInt16Array(byte[] data)
{
    //the length of data should be an even number
    int length = data.Length >> 1;
    short[] array = new short[length];
    fixed(byte* ptr = data) 
    {
        short* value = (short*)ptr;
        for (int i = 0; i < length; i++, value++) 
        {
            array[i] = (short)*value;
        }
    }
    return array;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)