2017-02-25 78 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

相關問題