【发布时间】:2015-10-27 19:09:24
【问题描述】:
我需要将00001110 等8 位数字转换为char。问题很简单,所以我写了代码,一切正常,但现在我需要尽可能地优化速度。
在测试类中:
class Program
{
static void Main(string[] args)
{
Random r = new Random();
int[] testTab = new int[8];
Normal n = new Normal();
long time;
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 9000; i++)
{
for (int j = 0; j < 8; j++)
{
testTab[j] = r.Next(2);
}
n.SetTable(testTab);
n.Decode();
}
watch.Stop();
time = watch.ElapsedTicks;
Console.WriteLine(time);
time = watch.ElapsedMilliseconds;
Console.WriteLine(time);
Console.ReadKey();
}
}
和算法类:
class Normal
{
private int[] _tab = new int[8];
public void SetTable(int[] tab)
{
_tab = tab;
}
public void Decode()
{
char a = ((char)( _tab[0]*1 + _tab[1]*2 + _tab[2]*4 + _tab[3]*8 + _tab[4]*16 + _tab[5]*32 +
_tab[6]*64 + _tab[7]*124));
}
}
在 9000 次的输出中,我得到了 2ms 的时间,这不是很长的时间(对于 9000 ),但我的 PC 中有很好的 proc。
最终代码将在智能手机中运行,因此没有强大的 CPU。在我的算法中,我使用随机数据,在最终版本中,我将通过相机加载数据(因此它会更长)并尝试在一秒钟内重复此操作 10 次,这就是为什么我在最小的操作中也需要最好的时间。
还有比这更快的将字节转换为字符的方法吗?
char a = ((char)( _tab[0]*1 + _tab[1]*2 + _tab[2]*4 + _tab[3]*8 + _tab[4]*16 + _tab[5]*32 + _tab[6]*64 + _tab[7]*128));
【问题讨论】:
-
为什么要使用
int[]表示比特?这些适合int!了解位操作:&、|、^ -
为什么不
Char result = (Char) (random.Next(256));? -
我使用 int 是因为我为测试而写,所以我不介意内存只需要时间 int 与字节的速度相同。最后我会尽可能小,但现在只是测试
-
@Aht 顺便说一句:
64*2=>128不是 124 -
真实数据从何而来?你真的需要二进制字符串吗?