C++ 一种返回十进制值作为二进制整数的方法,用 bool 数组表示

标签 c++ arrays binary

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/

相关文章:

java - System.out.println() 如何处理二进制数据?

C++开始和结束不工作

c++ - Clang 不会在编译时为非 constexpr 变量计算 constexpr 函数的值

c - 带二进制参数的 IF 条件

Python-使用来自 psycopg2 的二进制复制表

java - 应该计算数组中所有对的代码无法正常工作

c++ printf float - 如何以编程方式指定精度?

c++ - 从类方法清除raylib中的背景会使窗口闪烁

ios - 将项目添加到 'Routine' 选项卡中的特定 TableView 部分。每一天都有自己的 list 或例程

c# - 从 byte[] 中删除尾随零?