RCI*_*CIX 8 .net c# byte short
我需要接受成对字节,输出短路,并输入短路和输出字节对.以下是我为此目的设计的功能:
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);
}
Run Code Online (Sandbox Code Playgroud)
我认为这是正确的,但我不确定.如果这不是正确的方法,那是什么?有没有办法在框架中做到这一点?
TJB*_*TJB 31
short number = 42;
byte[] numberBytes = BitConverter.GetBytes(number);
short converted = BitConverter.ToInt16(numberBytes);
Run Code Online (Sandbox Code Playgroud)
Ate*_*ral 20
更短版本(也改变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);
}
Run Code Online (Sandbox Code Playgroud)
字节数是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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,严格来说,左右移动是不必要的.我只是将它们放入对称中.另外,我个人建议你只学习按位算术冷,并跳过编写这样的辅助函数.恕我直言,不需要用如此根本的东西隐藏细节.
| 归档时间: |
|
| 查看次数: |
30352 次 |
| 最近记录: |