Iam trying to split a long hex string into individual bytes and store it in an integer vector using a CPP program. For example, my input string will like 09e1c5f70a65ac519458e7e53f36
and my expected output will be like 09 e1 c5 f7....
. But I am getting output like 0 e c f.....
. I am getting only half of the byte value. And I already referred this link for reference ([https://stackoverflow.com/questions/21365364/how-to-split-a-hex-string-into-stdvector ]) and I want to get the output without using boost library.
So, I tried the below code as mentioned in the above link.
Here is my code.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
int main(void)
{
std::string in("09e1c5f70a65ac519458e7e53f36");
size_t len = in.length();
std::vector<uint8_t> out;
for(size_t i = 0; i < len; i += 2) {
std::istringstream strm(in.substr(i, 2));
uint8_t x;
strm >> std::hex >> x;
out.push_back(x);
}
for (int i=0; i<out.size(); ++i)
std::cout << out[i] << ' ';
return 0;
}
my expected output will be like std::vector<uint8_t> out = {09,e1,c5,f7,0a,65,ac,51,94,58,e7,e5,3f,36}
This statement
strm >> std::hex >> x;
reads only one character.
You could declare the varable x
as having for example the type uint16_t
uint16_t x;
strm >> std::hex >> x;
out.push_back(x);
And to output elements of the vector you could write
std::cout << std::setfill( '0' ) << std::setw( 2 ) << std::hex << ( uint16_t )out[i] << ' ';