Search code examples
javac++bytebuffer

C++ equivalent of Java ByteBuffer?


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.

Solution

  • 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);
    }