我通常stringstream用来写入内存中的字符串.有没有办法在二进制模式下写入char缓冲区?请考虑以下代码:
stringstream s;
s << 1 << 2 << 3;
const char* ch = s.str().c_str();
Run Code Online (Sandbox Code Playgroud)
内存ch将如下所示:0x313233 - 字符1,2和3的ASCII代码.我正在寻找一种自己编写二进制值的方法.也就是说,我想在内存中使用0x010203.问题是我希望能够编写一个函数
void f(ostream& os)
{
os << 1 << 2 << 3;
}
Run Code Online (Sandbox Code Playgroud)
并决定使用什么样的流.像这样的东西:
mycharstream c;
c << 1 << 2 << 3; // c.data == 0x313233;
mybinstream b;
b << 1 << 2 << 3; // b.data == 0x010203;
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
Kei*_*thB 35
要读取和写入包含字符串流的流的二进制数据,请使用read()和write()成员函数.所以
unsigned char a(1), b(2), c(3), d(4);
std::stringstream s;
s.write(reinterpret_cast<const char*>(&a), sizeof(unsigned char));
s.write(reinterpret_cast<const char*>(&b), sizeof(unsigned char));
s.write(reinterpret_cast<const char*>(&c), sizeof(unsigned char));
s.write(reinterpret_cast<const char*>(&d), sizeof(unsigned char));
s.read(reinterpret_cast<char*>(&v), sizeof(unsigned int));
std::cout << std::hex << v << "\n";
Run Code Online (Sandbox Code Playgroud)
这给0x4030201了我的系统.
编辑:为了使插入和提取操作符(<<和>>)透明地工作,最好的办法是创建一个正确的派生streambuf,并将其传递给您想要使用的任何流.
您可以使用模板执行此类操作。例如:
//struct to hold the value:
template<typename T> struct bits_t { T t; }; //no constructor necessary
//functions to infer type, construct bits_t with a member initialization list
//use a reference to avoid copying. The non-const version lets us extract too
template<typename T> bits_t<T&> bits(T &t) { return bits_t<T&>{t}; }
template<typename T> bits_t<const T&> bits(const T& t) { return bits_t<const T&>{t}; }
//insertion operator to call ::write() on whatever type of stream
template<typename S, typename T>
S& operator<<(S &s, bits_t<T> b) {
return s.write((char*)&b.t, sizeof(T));
}
//extraction operator to call ::read(), require a non-const reference here
template<typename S, typename T>
S& operator>>(S& s, bits_t<T&> b) {
return s.read((char*)&b.t, sizeof(T));
}
Run Code Online (Sandbox Code Playgroud)
它可以使用一些清理功能,但是可以正常工作。例如:
//writing
std::ofstream f = /*open a file*/;
int a = 5, b = -1, c = 123456;
f << bits(a) << bits(b) << bits(c);
//reading
std::ifstream f2 = /*open a file*/;
int a, b, c;
f >> bits(a) >> bits(b) >> bits(c);
Run Code Online (Sandbox Code Playgroud)