I am having hexconvert function which takes hexadecimal string as input and converts it into the byte stream,when hex string is small it is working well with arrays,now I am having hex string of big size(of exe file),I am not getting how should I use this function with vectors to avoid memory issues.
please help me out..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void hexconvert( char *text, unsignedchar bytes[] )
{
int i;
int temp;
for( i = 0; i < 4; ++i )
{
sscanf( text + 2 * i, "%2x", &temp );
bytes[i] = temp;
}
}
int main(void)
{
std::string myString = " "; // assuming string of big size
vector<unsignedchar> hexString(myString.begin(), myString.end());
vector< unsignedchar> bytes;
hexconvert(hexString,bytes);
}
See, whatever code i have posted previously it was original, now as I am not familiar with the vector in c++, so want to know how function
void hexconvert( vector<unsigned char>& text, vector<unsigned char>& bytes )
{
}
should be written with vectors(previously i used char * and unsigned char[] in function) having similar functionality.
Almost exactly the same as you have there. After all, vector was designed to be able to be used as an almost drop-in replacement for an array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void hexconvert(const std::string& text, std::vector<unsignedchar>& bytes){
bytes.resize((text.size() + 1) / 2); // set the size of the vector
int temp;
for(std::size_t i = 0; i < text.size(); i += 2) {
sscanf(text.c_str() + i, "%2x", &temp);
bytes[i] = temp;
}
}
int main() {
std::string hexstring = ""; // assume string of big size
std::vector<unsignedchar> bytes;
hexconvert(hexstring, bytes);
}
That should be about what you want. I've taken the liberty of allowing you to directly pass a std::string. Be careful, though - I don't think I made that 'resize' command to set it to the right size. It should be all right, though.