c ++将整数向量转换为整数

时间:2018-01-17 18:25:07

标签: c++ vector converter

正在网上搜索一个简单的指南,但无法找到。

我构建了一个从十进制到二进制的转换器,并将1&0; s和0保存在向量中。我现在想要将该向量转换为一个整数。 我发现转换为字符串而不是整数的各种方式(我没有真正理解)可以避免吗? 我希望尽可能简单。

这是我的代码:

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

我为你写了这样的smth:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> myNumInVect = {1, 1, 0, 0, 1};
    int myNumInInteger = 0;
    int baseOfMyNumInVector = 2;
    for (int i : myNumInVect) {
        myNumInInteger = myNumInInteger * baseOfMyNumInVector + i;
    }
    cout << myNumInInteger;
    return 0;
}

(此代码的输出为预期的25(11001(2)= 25(10))

它使用Horner's method,因此操作次数'*'= vector.size()。它很容易适应其他基地位置数字系统矢量(通过改变baseOfMyNumInVector)。

----------- @编辑-----------

我知道你拥有它,但我也想告诉你如何轻松完成转换dec2givenBase没有任何战争,或像这样的smth:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    int myNumInInteger = 111;
    int baseOfMyNumInVector = 2;
    vector<int> myNumInVect;

    while (myNumInInteger > 0) { // using Horner Scheme for switching base
        myNumInVect.push_back(myNumInInteger % baseOfMyNumInVector);
        myNumInInteger /= baseOfMyNumInVector;
    }

    std::reverse(myNumInVect.begin(), myNumInVect.end()); // reverse (bcs there is no push_front() method in vector)

    if (myNumInVect.empty()) { // handling the 0 case
        myNumInVect.push_back(0);
    }

    for (auto digit : myNumInVect) { // write the result
        cout << digit;
    }
    return 0;
}