簡體   English   中英

用std :: stringstream讀/寫無符號字節

[英]Reading/Writing unsigned bytes with std::stringstream

我試圖將未簽名的字符寫入字符串流。

我需要寫的信息涉及0x00。 我需要將0到40的值寫為實際數字值,而不是ASCII字符。

編輯:為了澄清,我寫的不只是值0-40。 它必須是二進制的。 這些進來的東西需要保持原樣,而不是一旦寫入流就變成字符。

以下是我正在做的事情。

TCHAR _buffer[2];    // This is part of the problem, I figure, since its a char
_buffer[0] = 0x00;
_buffer[1] = 0x01;

tstringstream s;

s.write(_buffer, sizeof(_buffer));

最終發生的是0x00導致字符串流結束,而0x01似乎從未到達那里。

我正在以類似的方式閱讀:

stream.readsome(_buffer, sizeof(_buffer));

由於寫入0x00並導致整個過程結束,因此似乎並不想發揮出色。

就是這樣嗎,還是我錯過了什么? 我試過使用ios_base :: binary,也試過使用uint8_t而不是TCHAR,但這似乎造成了很多混亂。 我擔心這可能是必需的路線,但是我想在開始之前先確定一下。

長話短說,我正在嘗試找到與C#的BinaryReader / Writer等效的C ++。

謝謝!

以下是在VS2012上編譯的:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    wchar_t buf[] = { 0x0, 0x1, 'a', 'b', 'c' };

    std::wstring s(buf);

    std::wstringstream ss;

    ss.write(buf, 5);

    const std::wstring& chars = ss.str();

    for (std::wstring::const_iterator it = chars.begin(); it != chars.end(); ++it)
        std::cout << std::hex << *it << '\n';

}

0 1 61 62 63按任意鍵繼續。

我想這就是你想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM