どのように変換するにはchar配列を文字列に基づく六角レンチ-ストリーム(ostringstream)

StackOverflow https://stackoverflow.com/questions/3802059

  •  25-09-2019
  •  | 
  •  

質問

C++で(Linuxでgcc)思入れるバイト配列(vector<unsigned char>ostringstream または string.

私が使用できます sprintf ないよう最良の方法の利用 char* ます。

ちなみ: このリンクかったな

編集: すべての解答の仕事です。なかったmeantionと思に変換するバイト/六角レンチの値を文字列表現は、例えば、 vector<..> = {0,1,2} -> string = "000102".まれることを見出が重要な詳細

役に立ちましたか?

解決

のアップ票を得るためのリトルチャンス、それはの正確のであるため、OPはのために聞くと、選択されたものを含む他の答えは、奇妙な、そうしません何ます:

#include <iostream>
#include <sstream>
#include <vector>
#include <iomanip>

// used by bin2hex for conversion via stream.
struct bin2hex_str
{
    std::ostream& os;
    bin2hex_str(std::ostream& os) : os(os) {}
    void operator ()(unsigned char ch)
    {
        os << std::hex
        << std::setw(2)
        << static_cast<int>(ch);
    }
};

// convert a vector of unsigned char to a hex string
std::string bin2hex(const std::vector<unsigned char>& bin)
{
    std::ostringstream oss;
    oss << std::setfill('0');
    std::for_each(bin.begin(), bin.end(), bin2hex_str(oss));
    return oss.str();
}

// or for those who wish for a C++11-compliant version
std::string bin2hex11(const std::vector<unsigned char>& bin)
{
    std::ostringstream oss;
    oss << std::setfill('0');
    std::for_each(bin.begin(), bin.end(),
        [&oss](unsigned char ch)
        {
            oss << std::hex
            << std::setw(2)
            << static_cast<int>(ch);
        });
    return oss.str();
}
<時間>

代替ストリームダンプ

あなたがやりたいすべてがunsigned char型の固定配列をダンプする場合は、次の意志の手近の、そう、すべてのほとんどのオーバーヘッドれます。

template<size_t N>
std::ostream& operator <<(std::ostream& os, const unsigned char (&ar)[N])
{
    static const char alpha[] = "0123456789ABCDEF";
    for (size_t i=0;i<N;++i)
    {
        os.put(alpha[ (ar[i]>>4) & 0xF ]);
        os.put(alpha[ ar[i] & 0xF ]);
    }
    return os;
}

私はのostreamのderivitiveに固定バッファをダンプしたいすべての時間、これを使用しています。コールは、デッドシンプルです:

unsigned char data[64];
...fill data[] with, well.. data...
cout << data << endl;

他のヒント

STL文字列へのベクトルのchar編曲から

std::string str(v.begin(), v.end());
ベクトルchar配列にSTL文字列から

std::string str = "Hellow World!";
std::vector<unsigned char> v(str.begin(), str.end());
setw含めるために

#include <iomanip>

このストリームに01を置く必要があります:

std::ostringstream oss;

unsigned char byte = 0x01;
oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(byte);

を使用するの ブースト:: alogorithm ::進する

std::vector<unsigned char> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);

の場合はstd :: ostreamに

std::ostream ss;
boost::algorithm::hex(v.begin(), v.end(), std::ostream_iterator<char>(ss));

のstd :: stringに

std::string res;
boost::algorithm::hex(v.begin(), v.end(), back_inserter(res));

あなたは文字列に文字のベクトルのデータを入れたいので?簡単ます:

string str;
str.resize(vec.size());
for (int n=0;n<vec.size();n++) {
  str[n] = vec[n];
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top