Good way to convert between short and bytes?

后端 未结 5 1459
攒了一身酷
攒了一身酷 2021-01-02 09:30

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:

s         


        
5条回答
  •  Happy的楠姐
    2021-01-02 10:26

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

提交回复
热议问题