C++ equivalent of Java ByteBuffer?

user172783 picture user172783 · Sep 23, 2009 · Viewed 30.6k times · Source

I'm looking for a C++ "equivalent" of Java ByteBuffer.

I'm probably missing the obvious or just need an isolated usage example to clarify. I've looked through the iostream family & it looks like it may provide a basis. Specifically, I want to be able to:

  • build a buffer from a byte array/point and get primitives from the buffer, e.g. getByte, getInt
  • build a buffer using primitives e.g. putByte, putInt and then get the byte array/pointer.

Answer

AraK picture AraK · Sep 23, 2009

You have stringbuf, filebuf or you could use vector<char>.


This is a simple example using stringbuf:

std::stringbuf buf;
char data[] = {0, 1, 2, 3, 4, 5};
char tempbuf[sizeof data];

buf.sputn(data, sizeof data); // put data
buf.sgetn(tempbuf, sizeof data); // get data

Thanks @Pete Kirkham for the idea of generic functions.

#include <sstream>

template <class Type>
std::stringbuf& put(std::stringbuf& buf, const Type& var)
{
    buf.sputn(reinterpret_cast<const char*>(&var), sizeof var);

    return buf;
}

template <class Type>
std::stringbuf& get(std::stringbuf& buf, Type& var)
{
    buf.sgetn(reinterpret_cast<char*>(&var), sizeof(var));

    return buf;
}

int main()
{
    std::stringbuf mybuf;
    char byte = 0;
    int var;

    put(mybuf, byte++);
    put(mybuf, byte++);
    put(mybuf, byte++);
    put(mybuf, byte++);

    get(mybuf, var);
}