【问题标题】:C++ A method that returns the decimal value as an integer of a binary that is represented with a boolean arrayC++ 一种将十进制值作为二进制整数返回的方法,用布尔数组表示
【发布时间】:2015-01-10 03:51:22
【问题描述】:

布尔数组为 1 为真,为 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;
}

感谢您的帮助!

【问题讨论】:

  • 输入数组中的数字是否有符号表示?
  • @MarkB:int 的符号在其最高位。因此,如果数组大小为<= numeric_limits<int>::digits,则该数组表示一个无符号数。如果数组的大小是== numeric_limits<int>::digits+1,则最后一个数组元素指定符号。 numeric_limits<int>::digits 不计算符号位。

标签: c++ arrays binary


【解决方案1】:

我想在不使用 pow() 的情况下执行此操作

pow() 用于2 的幂是一种矫枉过正,至少在二进制硬件上是这样。你可以使用

int mask = 1 << bitNumber;

生成一个int,除了bitNumber,所有位都设置为零。

可以记录我需要乘以加到总数中的数量

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

res |= 1 << bitNumber;

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

【讨论】:

  • 谢谢!我会研究一下什么是 bitwize "OR"。
【解决方案2】:
int mul = 1;
int accum = ;
for(int i = size - 1; i > 0; i++) {
    accum+=mul*binaryArray[i];
    mul*=2;
}

类似的东西。

【讨论】:

  • @Bapho 是的,我写得很快。
【解决方案3】:

试试这样的:

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 2013-11-07
    • 2012-03-31
    • 2011-07-28
    • 2017-08-22
    • 2014-10-05
    • 2020-04-28
    相关资源
    最近更新 更多