简体   繁体   中英

converting unsigned char* to std::istream* C++

I have to pass binary data (unsigned char*) to a function PerformRequest that takes std::istream as argument. What is the best

unsigned char* data // has the binary data

PerformRequest(std::istream* in)
{
    //some implementation
}

You can use an std::stringstream from <sstream> , which supports both istream and ostream interface. So you can write data through the ostream -interface and pass it then as an istream -argument:

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

void prints(istream &is) {
    unsigned char c;
    while (is >> c) {
        std::cout << "0x" << std::hex << (unsigned int)c << std::endl;
    }
}

int main()
{
    unsigned char x[6] = { 0x2, 0x10, 0xff, 0x0, 0x5, 0x8 };
    std::stringstream xReadWrite;
    xReadWrite.write((const char*)x, 6);
    prints(xReadWrite);
}

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