1

さまざまな構造体をファイルにシリアル化する必要があります。可能であれば、ファイルを純粋な ASCII にしたいと思います。構造体ごとにある種のシリアライザーを作成することもできますが、正確に表現したいfloats とs を含むものは何百もあります。double

サードパーティのシリアライゼーション ライブラリを使用できず、何百ものシリアライザを作成する時間がありません。

このデータを ASCII セーフにシリアル化するにはどうすればよいですか? またストリームしてください、私は C-style の見た目が嫌いですprintf("%02x",data)

4

2 に答える 2

2

このソリューションをオンラインで見つけましたが、この問題だけに対処しています。

https://jdale88.wordpress.com/2009/09/24/c-anything-tofrom-a-hex-string/

以下に再現:

#include <string>
#include <sstream>
#include <iomanip>


// ------------------------------------------------------------------
/*!
    Convert a block of data to a hex string
*/
void toHex(
    void *const data,                   //!< Data to convert
    const size_t dataLength,            //!< Length of the data to convert
    std::string &dest                   //!< Destination string
    )
{
    unsigned char       *byteData = reinterpret_cast<unsigned char*>(data);
    std::stringstream   hexStringStream;

    hexStringStream << std::hex << std::setfill('0');
    for(size_t index = 0; index < dataLength; ++index)
        hexStringStream << std::setw(2) << static_cast<int>(byteData[index]);
    dest = hexStringStream.str();
}


// ------------------------------------------------------------------
/*!
    Convert a hex string to a block of data
*/
void fromHex(
    const std::string &in,              //!< Input hex string
    void *const data                    //!< Data store
    )
{
    size_t          length      = in.length();
    unsigned char   *byteData   = reinterpret_cast<unsigned char*>(data);

    std::stringstream hexStringStream; hexStringStream >> std::hex;
    for(size_t strIndex = 0, dataIndex = 0; strIndex < length; ++dataIndex)
    {
        // Read out and convert the string two characters at a time
        const char tmpStr[3] = { in[strIndex++], in[strIndex++], 0 };

        // Reset and fill the string stream
        hexStringStream.clear();
        hexStringStream.str(tmpStr);

        // Do the conversion
        int tmpValue = 0;
        hexStringStream >> tmpValue;
        byteData[dataIndex] = static_cast<unsigned char>(tmpValue);
    }
}

stringstreamこれは、ファイル ストリームへの読み取り/書き込みに簡単に適用できますfromHex

于 2013-07-03T15:56:44.947 に答える