C++将整数 vector 转换为整数

标签 c++ vector converters

正在网上搜索简单指南,但找不到。

我构建了一个从十进制到二进制的转换器,并将 1 和 0 保存在一个 vector 中。我现在想将该 vector 变成一个整数。 我找到了各种方法(我不太了解)转换为字符串而不是整数,可以避免吗? 我希望它尽可能简单。

这是我的代码:

c.hpp:

#ifndef C_HPP
#define C_HPP
#include <vector>


class Dualrechnung{
private:
    std::vector<int> vec;
    int z = 123456; //Eingegebene Zahl
    int t_z = z; //temp Zahl

public:
    Dualrechnung();
    ~Dualrechnung();
};

#endif

c.cpp:

#include <vector>
#include <cmath>
#include <sstream>
#include "c.hpp"
#include <iostream>


Dualrechnung::Dualrechnung()
{
    int b;
        for (int i=0; (t_z-(pow(2,i))) >= 0; i++) //finds biggest power of 2 in z
        {
            b= i;
        }
        t_z-=pow(2,b); //whats left after the biggest power 
        vec.push_back(1);
    for(int i = b; i > 0; --i) //checks for every power of 2 multiples smaller than b if they exist in z. if they are, saves 1 for that power in the vector and if not, saves 0.
    {
        b--;
        if((t_z-pow(2,b)) >= 0)
            {
                vec.push_back(1);
                t_z-=pow(2,b);
            }
        else{vec.push_back(0);}
    }

// here I'd like that integer with the information from the vector

    int bin; //binary value of z
        std::cout << z << " in Dual ist " << bin;

}


Dualrechnung::~Dualrechnung(){}

c_test.cpp:

#include "c.cpp"
#include <iostream>


int main(){

    Dualrechnung *d = new Dualrechnung();
    delete d;
    return 0;
}

最佳答案

如果我理解正确,您需要将 int 转换为一组位,反之亦然。只需使用 std::bitset它具有来自 unsigned long 的构造函数和将其转换回来的方法(您也可以将其转换为 0 和 1 的字符串/从字符串转换)。

关于C++将整数 vector 转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48307664/

相关文章:

c++ - 从文件 C++ 中保存和读取双 vector

java - 如何自动转换十六进制代码以将其用作 Java 中的 byte[]?

c++ - 如何使用 vector 来存储形状?

java - 为什么 Vector.indexOf 方法不适用于此类?

java - BeanIO - 如何将 null 分配给空列表

c# - 集合更新后转换器未触发

c++ - 为没有的库类编写构造函数

c++ - 如何在 SQLite 中插入新行 ("\n") 字符?

c++ - 哪个转换应该与模板类参数一起使用,dynamic_cast 还是 reinterpet_cast?

c++ - 如何在 makefile 的同一列中打印 {done}