I need to convert a part of vector
s of char
s to an 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.
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.
The reason copying didn't work is probably because of endianness, assuming the first
char
is the most significant:Try this:
1.Take the address of the begin and end (one past the end) index.
2.Construct a std::string from it.
3.Feed it into a std::istringstream.
4.Extract the integer from the stringstream into a variable.
(This may be a bad idea!)
If the positions are known, you can do it like this
This is fairly flexible, although it doesn't check for overflow or anything fancy like that: