问题描述
有人可以建议更好的方法来实现GetUInt16()方法吗?
它可以正常但是我想删除开关()声明如果可能的话。
谢谢,
Russell Mangel
拉斯维加斯,NV
使用系统;
类程序
{
static void Main(string [] args)
{
//比特头寸是LSB(最低有效位)如下:0,1,2,3,4,5,6,7
//我对第4和第5位感兴趣。
String [] values = {" 00000000"," 00000100"," 00001000"," 00001100" };
//测试所有四个可能的值
foreach(值中的字符串值)
{
UInt16 returnValue = GetUInt16(Convert.ToByte(value,2));
if(returnValue!= 0xFFFF)
{
Console.WriteLine(returnValue);
}
}
Console.ReadLine();
}
私有静态UInt16 GetUInt16(字节b)
{
//此代码工作正常,你能简单一点吗?
//有没有办法在一两行中做到这一点?
UInt16值= 0xFFFF;
开关(b& 0x0C)
{
案例0x00:
value = 0; // 00000000
休息;
案例0x04:
value = 1; // 00000100
休息;
案例0x08:
value = 2; // 00001000
休息;
案例0x0C:
value = 3; // 00001100
休息;
}
返回值;
}
}
Hi,
Can someone suggest a better way to implement the GetUInt16() method?
It works okay but I would like to remove the switch() statement if possible.
Thanks,
Russell Mangel
Las Vegas, NV
using System;
class Program
{
static void Main( string[] args )
{
// Bit positions are LSB (least significant bit) as follows: 0,1,2,3,4,5,6,7
// I am interested in bits 4 and 5.
String[] values = { "00000000", "00000100", "00001000", "00001100" };
// Test all four possible values
foreach ( String value in values )
{
UInt16 returnValue = GetUInt16( Convert.ToByte( value, 2 ) );
if ( returnValue != 0xFFFF )
{
Console.WriteLine( returnValue );
}
}
Console.ReadLine( );
}
private static UInt16 GetUInt16( Byte b )
{
// This code works fine, can you simplfy it?
// Is there some way to do this in one or two lines?
UInt16 value = 0xFFFF;
switch ( b & 0x0C )
{
case 0x00:
value = 0; // 00000000
break;
case 0x04:
value = 1; // 00000100
break;
case 0x08:
value = 2; // 00001000
break;
case 0x0C:
value = 3; // 00001100
break;
}
return value;
}
}
推荐答案
如果它没有破坏......不要修复它。
RL
If it ain''t broke...don''t fix it.
RL
你能不能把它换成两位?
Jon
Can''t you just shift it right two bits?
Jon
这篇关于只有位小提琴手:你能简化这个C#代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!