[英]convert vector of char to an int
I need to convert a part of vector
s of char
s to an int
. 我需要将
char
的vector
的一部分转换为int
。
If I have 如果我有
std::vector<char> // which contains something like asdf1234dsdsd
and I want to take characters from the 4th till 7th position and convert it into an int. 我想从第4位到第7位采取字符并将其转换为整数。
The positions are always known. 位置总是已知的。
How do I do it the fastest way ? 我如何最快地做到这一点?
I tried to use global copy and got a weird answer. 我试图使用全局副本,但得到了一个奇怪的答案。 Instead of 2 I got 48.
而不是2,我得到了48。
如果位置已知,您可以这样操作
int x = (c[4] - '0') * 1000 + (c[5] - '0') * 100 + (c[6] - '0') * 10 + c[7] - '0';
复制不起作用的原因可能是由于字节顺序,假设第一个char
是最重要的:
int x = (int(c[4]) << 24) + (int(c[5]) << 16) + (int(c[6]) << 8) + c[7]
This is fairly flexible, although it doesn't check for overflow or anything fancy like that: 这是相当灵活的,尽管它不检查溢出或类似的东西:
#include <algorithm>
int base10_digits(int a, char b) {
return 10 * a + (b - '0');
}
int result = std::accumulate(myvec.begin()+4, myvec.begin()+8, 0, base10_digits);
1.Take the address of the begin and end (one past the end) index. 1.获取开始和结束(末尾一个)索引的地址。
2.Construct a std::string from it. 2.从中构造一个std :: string。
3.Feed it into a std::istringstream. 3.将其输入到std :: istringstream中。
4.Extract the integer from the stringstream into a variable. 4,将字符串流中的整数提取为变量
(This may be a bad idea!) (这可能是个坏主意!)
Try this: 尝试这个:
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int vtoi(vector<char> vec, int beg, int end) // vector to int
{
int ret = 0;
int mult = pow(10 , (end-beg));
for(int i = beg; i <= end; i++) {
ret += (vec[i] - '0') * mult;
mult /= 10;
}
return ret;
}
#define pb push_back
int main() {
vector<char> vec;
vec.pb('1');
vec.pb('0');
vec.pb('3');
vec.pb('4');
cout << vtoi(vec, 0, 3) << "\n";
return 0;
}
long res = 0;
for(int i=0; i<vec.size(); i++)
{
res += vec[i] * pow (2, 8*(vec.size() - i - 1)); // 8 means number of bits in byte
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.