2011-06-13 36 views
0

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

+3

我不确定你的“直觉”在这里......你可以举一些更多的输入和输出的例子,以及*为什么*?例如,为什么不忽略底部位呢? – 2011-06-13 14:32:47

+0

除了'ushort.MaxValue'之外,还有哪些值应该转换为? – 2011-06-13 14:44:26

+0

是的。你对我的直觉完全错误是正确的。 – 2011-06-13 15:37:30

回答

1

是这样的吗?

// 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) 
+0

如果您打算倒下我的答案,至少请说明原因。批评帮助我们学习... :) – CodingWithSpike 2011-06-13 14:47:27

+1

快速注意,为了将来参考,由于整数除法,比率将始终为零。可用的许多修补程序中,255.0/65535可能是最简单的。 (我没有downvote) – 2011-06-13 14:47:57

+0

@Corey Ogburn - 好点,谢谢你的收获。 – CodingWithSpike 2011-06-13 15:01:32

0

我会除以256并将该值设置为一个字节。你可以确定你是否想要舍弃它,但是当你试图将一个值缩小到一个更小的值时,创建一些过于复杂的位掩码方法似乎有点苛刻。如果只有0 == 0和65535 = 256,那么你可能不想把事情弄糟。我错过了什么吗?

1
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--; 
    } 
} 
+0

我喜欢它。我可能会对此进行速度测试。 – 2011-06-15 07:47:27

2

记住顶位是“最显著” - 这意味着他们应该是缩小尺寸时要保留的尺寸。

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

你的方式,0x0001将是0x01,但0x0002将是0x00,这是奇怪的。

相关问题