[英]Is there a good way to convert between BitmapSource and Bitmap?
[英]Good way to convert between short and bytes?
我需要将字节对放入 output 短裤,将短裤放入 output 字节对。 以下是我为此目的设计的功能:
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);
}
我认为这是正确的,但我不确定。 如果这不是正确的方法,那什么才是? 有没有办法在框架中做到这一点?
short number = 42;
byte[] numberBytes = BitConverter.GetBytes(number);
short converted = BitConverter.ToInt16(numberBytes);
较短的版本(也将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);
}
字节是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);
}
请注意,严格来说,左移和右移都不为零。 我只是为了对称而提出。 另外,我个人建议您只学习按位算术,并跳过编写此类辅助函数。 恕我直言,无需使用如此基本的内容隐藏细节。
如果您想获取字节...请获取字节; 并且您的班次停止了,并且|
会更直观:
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
在 .net 5/6 或 .net 标准 2.0+ 中,或者如果您使用 .NET Fx,则可以在 Nuget 中添加System.Memory
var body = new byte[2];
short counter = 2;
MemoryMarshal.Write(body.AsSpan(0,2), ref counter);
现在,短计数器已经转换为字节;
如果你想把它转换回来,你只需要
short counter = (short)(body[0] + body[1]);
就这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.