在短和字节之间转换的好方法?

我需要接受成对字节,输出短路,并输入短路和输出字节对。 以下是我为此目的设计的function:

static short ToShort(short byte1, short byte2) { short number = (short)byte2; number <> 4); short tempByte = (short)byte2 << 4; byte byte1 = (byte)(number - tempByte); } 

我认为这是正确的,但我不确定。 如果这不是正确的方法,那是什么? 有没有办法在框架中做到这一点?

更短版本(也改变8位而不是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); } 

使用BitConverter

 short number = 42; byte[] numberBytes = BitConverter.GetBytes(number); short converted = BitConverter.ToInt16(numberBytes); 

字节数是8位,而不是4位,所以你的移位是关闭的。 您还在第二个函数中声明了局部变量,因此您最终不会像想要的那样编​​写out参数。 如果你在可能的情况下将自己限制为按位运算( &|~ ),那么它也更清晰/更好。

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

请注意,严格来说,左右移动是不必要的。 我只是将它们放入对称中。 另外,我个人建议你只学习逐位算术冷,并跳过编写这样的辅助函数。 恕我直言,不需要用如此根本的东西隐藏细节。

如果你想取字节…取字节; 你的class次已经结束,而且 会更直观:

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

System.BitConverter