简体   繁体   English

向量C ++中字节表示形式的int

[英]Int from byte representation in vector c++

I have a vector<int> of length n which contains only 0 and 1's. 我有一个长度为n的vector<int> ,其中仅包含0和1。 For example we can have the following vector of length 10: 例如,我们可以具有以下长度为10的向量:

0 1 1 0 1 0 0 1 0 0

Now I use the number represented by that vector to access a location in an array with 2^n entries (so in this case an array of 2^10 = 1024). 现在,我使用该向量表示的数字来访问具有2 ^ n个条目的数组中的位置(因此,在本例中为2 ^ 10 = 1024的数组)。 I'm not sure how I can obtain one integer from the byte representation stored in this vector<int> . 我不确定如何从此vector<int>存储的字节表示形式中获取一个整数。

Simply run through the vector and collect powers of 2. 只需遍历向量并收集2的幂。

It depends on which end of the vector you want as most significant digit but eg 它取决于您想要向量的最高有效位,但是例如

auto to_int( const vector<int>& digits )
    -> int
{
    int result = 0;
    for( int const digit : digits )
    {
        result += 2*result + digit;
    }
    return result;
}

Or the other way, 或相反,

auto to_int( const vector<int>& digits )
    -> int
{
    int result = 0;
    for( int i = (int)digits.size();  i --> 0; )
    {
        result += 2*result + digits[i];
    }
    return result;
}

Disclaimer: code not reviewed by compiler. 免责声明:编译器未审查代码。

使用具有to_ulong()方法的std :: bitset( http://en.cppreference.com/w/cpp/utility/bitset

A simply way using a for loop: 使用for循环的简单方法:

size_t val{0};
for (const auto i : vec)
    val = (val << 1) + i;

Something like this: 像这样:

int integer=0;
int c=0;
for(int i : intVector){
    integer+=i<<c;
    c++;
}
return integer;

You can keep the std::vector and use std::bitset : 您可以保留std::vector并使用std::bitset

#include <iostream>
#include <vector>
#include <bitset>
#include <algorithm>
#include <climits>

template <typename IterType>
unsigned long getValue(IterType i1, IterType i2)
{
    unsigned long i = 0;
    std::bitset<CHAR_BIT * sizeof(unsigned long)> b;
    std::for_each(i1, i2, [&](auto n) { b.set(i++, n);});
    return b.to_ulong();
}

int main() 
{
    std::vector<int> v = {0, 1, 1, 0, 1, 0, 0, 1, 0, 0};
    auto val = getValue(v.rbegin(), v.rend());
    std::cout << val << "\n";;  
    auto val2 = getValue(v.begin(), v.end());
    std::cout << val2;  
}

Note that depending on which bit is the most significant bit, you supply the iterators accordingly. 请注意,根据哪个位是最高有效位,可以相应地提供迭代器。 For right-to-left, supply reverse iterators, otherwise supply forward iterators. 对于从右到左,请提供反向迭代器,否则请提供正向迭代器。

Live Example 现场例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM