Good way to convert between short and bytes?

后端 未结 5 1469
攒了一身酷
攒了一身酷 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条回答
  •  佛祖请我去吃肉
    2021-01-02 10:15

    If you want to take bytes... take bytes; and your shifts are off, and | would be more intuitive:

    static short ToShort(byte byte1, byte byte2)
    {   // using Int32 because that is what all the operations return anyway...
        return (short)((((int)byte1) << 8) | (int)byte2);
    }
    static void FromShort(short number, out byte byte1, out byte byte2)
    {
        byte1 = (byte)(number >> 8); // to treat as same byte 1 from above
        byte2 = (byte)number;
    }
    

提交回复
热议问题