类型转换-What';s是在c#中将ushort转换为字节的最快方法

本文关键字:字节 转换 方法 ushort 中将 -What 是在 类型转换 | 更新日期: 2023-09-27 17:58:57

我想将ushort转换为一个字节,这样如果ushort等于ushort。MaxValue,那么字节等于0xFF,如果ushort等于零,那么字节就等于0x00。直观地说,这意味着去掉ushort位数组中的每一个其他位。在c#中,最有效的方法是什么?

类型转换-What';s是在c#中将ushort转换为字节的最快方法

请记住,最高位是"最重要的",这意味着它们应该是您在缩小时想要保留的。

您应该将8右移(或除以256)——在这种情况下,MaxValue将为0xFF,0也将为0x00。

按照您的方式,0x0001将是0x01,但0x0002将是0x00,这很奇怪。

类似的东西?

// set this in a constructor or something.
// it is constant and does not need recalcualted each time.
private float ratio = 255 / 65535; // (or byte.MaxValue / ushort.MaxValue)
// do math
public byte Calcualte(ushort value)
{
    return (byte)value * ratio;
}
// test
Assert.AreEqual(byte.MinValue, Calcualte(ushort.MinValue));
Assert.AreEqual(byte.MaxValue, Calcualte(ushort.MaxValue));

编辑#1:

注意,上面使用了一些底部舍入,因此ushort.MaxValue - 1将变为字节254。使用Math.Round()可能更好,可能是:return (byte)Math.Round(value * ratio);


编辑#2:

你最初说:

直观地说,这意味着去掉ushort位数组中的每一个其他位。

我认为这是一个错误的说法,因为如果你每隔一点就放弃,那么你就会得到:

0000000000000000 => 00000000 (0 => 0 : correct)
0101010101010101 => 00000000 (21845 => 0 : incorrect)
1010101010101010 => 11111111 (43690 => 255 : incorrect)
1111111111111111 => 11111111 (65535 => 255 : correct)
 byte output = 0;
 //ushort us = value;
 if (us == ushort.MaxValue)
 {
     output = 0xff;
 }
 else
 {     
    ushort ush = us & 0xAAAA; // 0xAAAA => Bin 1010101010101010
    int i = 7;
    while(ush > 0)
    {
       output = output | ((ush & 0x0001) << i);
       ush = ush  >> 2;                  
       i--;
    }
 }

我将除以256并将该值设置为一个字节。你可以决定是否要四舍五入,但当你只是试图将一个值缩小到一个较小的集合时,创建一些过于复杂的位掩码方法似乎有点苛刻。如果只有0==0和65535=256,那么你可能不想四舍五入。我遗漏了什么吗?