我刚开始学习D语言,现在我需要像这样读写数据:
byte[] bytes = ...;
ByteBuffer buf = new ByteBuffer(bytes);
int a = buf.getInt();
byte b = buf.getByte();
short s = buf.getShort();
buf.putInt(200000);
有没有D语言内置的工具可以实现这个功能,还是我必须自己编写?
我刚开始学习D语言,现在我需要像这样读写数据:
byte[] bytes = ...;
ByteBuffer buf = new ByteBuffer(bytes);
int a = buf.getInt();
byte b = buf.getByte();
short s = buf.getShort();
buf.putInt(200000);
read
、peek
、write
和 append
。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[]
)的自由函数 - 因此它们可能不完全像您所需的那样工作,但它们是为需要从数组或其他字节范围中提取整数值的情况而设计的。如果您真的想要某种单独的缓冲类型,那么您应该能够相当容易地创建一个内部使用它们的缓冲类型。
旧的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源代码的私人副本。
bitmanip
默认为Endian.bigEndian
。 - deceleratedcaviar