简体   繁体   中英

How to convert IStream to Base64 string in c++

I have IStream and I want to convert it to base 64 string in c++ so that I can use it in C++/cli to convert it to .net stream.

Similar way, I want to know how to convert base 64 string back to IStream.

My code uses ATL CString...

template<class T>
HRESULT StreamToBase64(IStream* pStream, T &strOut)
{
    // Clear buffer
    strOut.ReleaseBuffer(0);
    if (!pStream)
        return S_OK;

    // Get size
    STATSTG stat;
    pStream->Stat(&stat, STATFLAG_NONAME);
    unsigned iLen = stat.cbSize.LowPart;

    // Seek to start
    LARGE_INTEGER lPos;
    lPos.QuadPart = 0;
    HRESULT hr = pStream->Seek(lPos, SEEK_SET, nullptr);
    if (FAILED(hr))
        return hr;

    // Reserve the memory
    strOut.GetBuffer(Mfx::BinToBase64GetRequiredLength(iLen));
    strOut.ReleaseBuffer(0);

    // Use one line to decode a time. On line of Base64 code has usually 39 chars. We
    // use a nearly 1kb buffer
    const int iBase64LIneLen = 76/4*3;
    BYTE bLine[(1024/iBase64LIneLen)*iBase64LIneLen];
    ULONG bRead;
    while (SUCCEEDED(hr = pStream->Read(bLine, sizeof(bLine), &bRead)) && bRead!=0)
        strOut += T(Mfx::BinToBase64A(bLine, bRead));

    // And seek back to start
    pStream->Seek(lPos, SEEK_SET, nullptr);
    return SUCCEEDED(hr) ? S_OK : hr;
}

HRESULT StreamToBase64(IStream* pStream, CStringA &strOut)
{
    return StreamToBase64<CStringA>(pStream, strOut);
}

HRESULT StreamToBase64(IStream* pStream, CStringW &strOut)
{
    return StreamToBase64<CStringW>(pStream, strOut);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM