将unsigned char转换为string然后再转换为unsigned char

时间:2018-04-09 11:45:52

标签: c++ converter unsigned-char

我想转换:

  1. 一个简单的unsigned char []string

  2. 然后再次使用unsigned char

  3. 这是我的代码:

    // This is the original char
    unsigned char data[14] = {
        0x68,0x65,0x6c,0x6c,0x6f,0x20,0x63,0x6f,0x6d,0x70,0x75,0x74,0x65,0x72,
    };
    
    // This convert to string
    string str(data, data + sizeof data / sizeof data[0]);
    
    // And this convert to unsigned char again
    unsigned char* val = new unsigned char[str.length() + 1];
    strcpy_s(reinterpret_cast<char *>(val), str.length()+1 , str.c_str());
    

    问题在于第二部分,它不会像以前那样将字符串转换为unsigned char。我认为this img from locals in debug有帮助

1 个答案:

答案 0 :(得分:1)

一种方式:

#include <string>
#include <utility>
#include <cstring>
#include <memory>
#include <cassert>

int main()
{
    // This is the original char
    unsigned char data[14] = {
        0x68,0x65,0x6c,0x6c,0x6f,0x20,0x63,0x6f,0x6d,0x70,0x75,0x74,0x65,0x72,
    };

    // This convert to string
    std::string str(std::begin(data), std::end(data));

    // And this convert to unsigned char again
    auto size = std::size_t(str.length());
    auto new_data = std::make_unique<unsigned char[]>(size);
    std::memcpy(new_data.get(), str.data(), size);

    // check
    for (auto f1 = data, f2 = new_data.get(), e1 = f1 + size ; f1 != e1 ; ++f1, ++f2)
    {
        assert(*f1 == *f2);
    }
}