How can I use this C++ code with vector?

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, unsigned char 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<unsigned char> hexString(myString.begin(), myString.end());
    vector< unsigned char> bytes;
    hexconvert(hexString,bytes);
    }
Surely your method prototype should be something like:

 
void hexconvert( vector<unsigned char>& text, vector<unsigned char>& bytes )


?
Last edited on
Yes, I want this function to be in the same format stated by you..
Oh i see now sorry. The way you wrote your issue it looked like you were saying it was working "as is", which was confusing me.

For formatting a std::string have a look here:
http://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprintf

You can access each element of your vector in the same way as you're doing on line, or explicitly use the at() method:
http://en.cppreference.com/w/cpp/container/vector/at

Remember to pass by reference too.
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<unsigned char>& 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<unsigned char> 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.
Topic archived. No new replies allowed.