将bool转换为字节的最快方法是什么? [英] What is fastest way to convert bool to byte?
本文介绍了将bool转换为字节的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将bool转换为字节的最快方法是什么?
What is fastest way to convert bool to byte?
我想要此映射:False = 0,True = 1
I want this mapping: False=0, True=1
注意:我不想使用任何 if
语句或其他条件语句。我不希望CPU停止运行或猜测下一条语句。
Note: I don't want to use any if
statements or other conditional statements. I don't want the CPU to halt or guess next statement.
更新:
对于那些想知道要点的人这个问题。
此示例显示了如何从代码中减少两个if语句。
Update: For those who want to see the point of this question. This example shows how two if statement are reduced from the code.
byte A = k > 9 ; //If it was possible (k>9) == 0 || 1
c[i * 2] = A * (k + 0x37) - (A - 1) * (k + 0x30);
推荐答案
使用不安全
编码此方法非常快。启用优化后,它比条件运算符快约30%。
Using unsafe
code this method is pretty fast. With optimizations enabled its about 30% faster than the conditional operator.
bool input = true;
byte value = *((byte*)(&input)); // 1
这篇关于将bool转换为字节的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文