java byte 与 c byte,C ++相当于Java ByteBuffer?

这篇博客介绍了如何在C++中使用stringbuf或vector来实现类似于Java ByteBuffer的功能。通过示例代码展示了如何构建和操作缓冲区,包括从字节数组/指针构建缓冲区,以及从缓冲区获取原始类型如字节和整数。模板函数put和get被用来方便地插入和读取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

解决方案

You have stringbuf, filebuf or you could use vector.

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

template

std::stringbuf& put(std::stringbuf& buf, const Type& var)

{

buf.sputn(reinterpret_cast(&var), sizeof var);

return buf;

}

template

std::stringbuf& get(std::stringbuf& buf, Type& var)

{

buf.sgetn(reinterpret_cast(&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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值