Johnnylin Johnnylin - 1 month ago 6
C++ Question

convert vector<char> first N elements to an integer

How Can I convert first

HEADER_LENGTH
of a
std::vector<char>
to an integer?

Here
HEADER_LENGTH
is the message size and
std::vector<char>
is the whole message.

UPDATE:

To clarify, It is combining first N elements, not just converting them separately.

Thanks.

Answer

I can't get your exactly idea so I do both my guesses.

#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

int main() {
    vector<char> a = {'0','1','2','3','4'};

//My sample is for HEADER_LENGTH of 4

    // by memory content
    int x;
    memcpy(&x, a.data(), 4);
    cout << x << endl; //858927408

    // by digit
    x = 0;
    for (auto it = 0; it < 4; it++) {
        x = x * 10 + (a[it] - '0');
    }
    cout << x << endl; //123
    return 0;
}
Comments