Search code examples
c#.netbyteshort

Good way to convert between short and bytes?


I need to take pairs of bytes in, and output shorts, and take shorts in and output pairs of bytes. Here are the functions i've devised for such a purpose:

static short ToShort(short byte1, short byte2)
{
    short number = (short)byte2;
    number <<= 4;
    number += (short)byte1;
    return number;
}
static void FromShort(short number, out byte byte1, out byte byte2)
{
    byte byte2 = (byte)(number >> 4);
    short tempByte = (short)byte2 << 4;
    byte byte1 = (byte)(number - tempByte);
}

I think this is correct but i'm not sure. If this isn't the right way to do it, what is? is there a way to do this already in the framework?


Solution

  • Shorter version (also shifting 8 bits instead of 4):

    static short ToShort(short byte1, short byte2)
    {
        return (byte2 << 8) + byte1;
    }
    
    static void FromShort(short number, out byte byte1, out byte byte2)
    {
        byte2 = (byte)(number >> 8);
        byte1 = (byte)(number & 255);
    }