bool 数组有 true 表示 1,false 表示 0。 8 将表示为 false false false true,其中 true 位于索引 3。6 将表示为 false、true、true。我也想在不使用 pow() 的情况下执行此操作。该方法会将十进制表示形式返回为整数。
我目前拥有的:
int Binary::binaryToInteger(bool *binaryArray, int size)
{
Something that will keep track of the index and something that will keep track of
the amount I need to multiply by added to a total and an if else that will take care
of true or false
return total;
}
感谢您的帮助!
最佳答案
I want to do this without using
pow()
使用 pow()
计算 2 的幂是一种矫枉过正,至少在二进制硬件上是这样。你可以使用
int mask = 1 << bitNumber;
生成一个 int
,所有位都设置为零,除了 bitNumber
将被设置为 1。
something that will keep track of the amount I need to multiply by added to a total
不需要乘法。至于加法,可以用按位“或”代替:
res |= 1 << bitNumber;
如果您遍历bool
值数组,将res
初始设置为零,并将上述操作应用于bitNumber
索引,其中binaryArray[bitNumber]
设置为 true
,那么 res
的最终值将对应于您定义的 int
bool
值数组。
关于C++ 一种返回十进制值作为二进制整数的方法,用 bool 数组表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27867818/