2017-02-25 79 views
2

这里是我写的打印的字节数组到十六进制字符串,但现在我想将其保存为的std :: string,并在以后使用它转换字节数组十六进制字符串

这里是我的代码

typedef std::vector<unsigned char> bytes; 
void printBytes(const bytes &in) 
{ 
    std::vector<unsigned char>::const_iterator from = in.begin(); 
    std::vector<unsigned char>::const_iterator to = in.end(); 
    for (; from != to; ++from) printf("%02X", *from); 
} 

我该怎么办?我想将它保存为字符串而不是在控制台窗口中打印(显示)? 任何想法!

+0

“* C++中有像StringBuilder的*无功能” - 是的,有。它被称为'std :: ostringstream'。 –

回答

2

使用std::ostringstream

typedef std::vector<unsigned char> bytes; 
std::string BytesToStr(const bytes &in) 
{ 
    bytes::const_iterator from = in.cbegin(); 
    bytes::const_iterator to = in.cend(); 
    std::ostringstream oss; 
    for (; from != to; ++from) 
     oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(*from); 
    return oss.str(); 
} 
+1

'static_cast ()'在C++中比C风格的''cast'(int)'更习惯。 – phoenix

+0

如果你想追加'0x'到前面,使用['std :: showbase'](http://en.cppreference.com/w/cpp/io/manip/showbase) – phoenix

+0

@phoenix你会怎么样去把这个字符串转换回来? – anc

相关问题