c++ - Store a string in a vector of unsigned long int -


i convert std::string std::vector<unsigned long int>, , able reverse it. currently, way :

std::string str = "hello world !"; std::vector<unsigned long int> keys; for(unsigned long int = 0; < str.length();) {   unsigned long int key = 0;   for(unsigned long int j = 0; j < sizeof(unsigned long int) && < str.length(); ++i,++j)   {     unsigned char uchar_value = static_cast<unsigned char>(str[i]);     unsigned long int ulong_value = static_cast<unsigned long int>(uchar_value);     key |= ulong_value << (j * char_bit);   }   keys.push_back(key); } 

then, have similar procedure reverse it. it's quite ugly ! is there better/more elegant way ? maybe directly memcpy ? don't see how.

what about:

std::string str = "hello world !"; std::vector<unsigned long int> keys(str.size() / sizeof(unsigned long int)+1);  std::copy(begin(str), end(str), reinterpret_cast<unsigned char*>(&(*keys.begin()))); 

and reverse:

std::string str2(keys.size()*sizeof(unsigned long int), '\0'); std::copy(reinterpret_cast<unsigned char*>(&*begin(keys)), reinterpret_cast<unsigned char*>(&*end(keys)), str2.begin()); str2.resize(str.size()); 

and if want store bytes in reverse order, can use reverse iterators:

std::string str = "hello world !"; std::vector<unsigned long int> keys(str.size() / sizeof(unsigned long int)+1);  std::copy(str.rbegin(), str.rbegin, reinterpret_cast<unsigned char*>(&(*keys.begin())));   

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -