C++ 一种方法,将returns十进制值作为二进制的整数,用布尔数组表示

C++ A method that returns the decimal value as an integer of a binary that is represented with a boolean array

布尔数组 1 为真,0 为假。 8 将表示为 false false false true,其中 true 位于索引 3。6 将表示为 false、true、true。我也想在不使用 pow() 的情况下执行此操作。该方法将return小数表示为整数。

我目前拥有的:

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 之外的所有位都设置为零。

something that will keep track of the amount I need to multiply by added to a total

不需要乘法。至于加法,可以按位换成"OR":

res |= 1 << bitNumber;

如果您遍历 bool 值的数组,最初将 res 设置为零,然后将上述操作应用于 bitNumber 索引,其中 binaryArray[bitNumber] 设置为true,那么 res 的最终值将对应于 bool 值数组定义的 int

int mul = 1;
int accum = ;
for(int i = size - 1; i > 0; i++) {
    accum+=mul*binaryArray[i];
    mul*=2;
}

类似的东西。

尝试这样的事情:

#include <limits>
#include <stdexcept> 

int Binary::binaryToInteger(bool *binaryArray, int size)
{
    if ((size < 0) || (size > (std::numeric_limits<int>::digits+1))) // +1 for sign bit, which digits ignores
        throw std::runtime_error("invalid size!");

    // The boolean array has true for 1 and false for 0.
    // 8 would be represented as "false false false true", where true is at index 3.
    // 6 would be "false, true, true".

    int result = 0;
    for (int i = 0; i < size; ++i)
    {
        if (binaryArray[i])
            result |= (1 << i);
    }

    return result;
}