D - 有没有适用于读写字节的ByteBuffer?

3

我刚开始学习D语言,现在我需要像这样读写数据:

byte[] bytes = ...;
ByteBuffer buf = new ByteBuffer(bytes);
int a = buf.getInt();
byte b = buf.getByte();
short s = buf.getShort();
buf.putInt(200000);

有没有D语言内置的工具可以实现这个功能,还是我必须自己编写?
2个回答

9
我建议查看 std.bitmanip 中的 read、peek、write 和 append 函数。例如:readpeekwriteappend
ubyte[] buffer = [1, 5, 22, 9, 44, 255, 8];
auto range = buffer; // if you don't want to mutate the original

assert(range.read!ushort() == 261);
assert(range == [22, 9, 44, 255, 8]);

assert(range.read!uint() == 369_700_095);
assert(range == [8]);

assert(range.read!ubyte() == 8);
assert(range.empty);
assert(buffer == [1, 5, 22, 9, 44, 255, 8]);

没有缓冲类型 - 相反,它们是操作ubyte范围(包括ubyte[])的自由函数 - 因此它们可能不完全像您所需的那样工作,但它们是为需要从数组或其他字节范围中提取整数值的情况而设计的。如果您真的想要某种单独的缓冲类型,那么您应该能够相当容易地创建一个内部使用它们的缓冲类型。


这应该是真正的答案。谢谢! - deceleratedcaviar
请注意,bitmanip 默认为 Endian.bigEndian - deceleratedcaviar

0

旧的std.stream模块应该可以胜任:http://dlang.org/phobos/std_stream.html#MemoryStream

MemoryStream buf = new MemoryStream(bytes);
// need to declare the variable ahead of time
int a;
// then read knows what to get due to the declared type
buf.read(a);
byte b;
buf.read(b);
but.write(200000); // that is an int literal so it knows it is int
buf.write(cast(ubyte) 255); // you can also explicitly cast

不过,页面上的警告说,Phobos维护者不喜欢这个模块,并想要将其删除...但他们已经这么说了好几年了,我建议你直接使用它。或者如果你愿意,可以制作一个stream.d源代码的私人副本。


2
使用Phobos中已弃用的符号,更不用说模块,总是一个坏主意。虽然std.stream有一段时间的注释说明它将被删除,但实际上并没有被弃用,但现在它已经被弃用了(这意味着使用它将会看到弃用消息 - 可能会有很多),并且它将被删除,在此之后仍在使用它的任何代码都将无法运行。因此,如果您想使用std.stream,请随意将其复制到自己的代码库中。 - Jonathan M Davis
1
下降投票,因为存在非弃用的解决方案。 - Bauss
1
如果有的话,那就写下你自己的答案吧! - DejanLekic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接