Equivalent of Java's “ByteBuffer.putType()” in C#

佐手、 提交于 2019-12-21 20:28:39

问题


I am trying to format a byte array in C#, by porting a code from Java. In Java, the methods "buf.putInt(value);", buf.putShort, buf.putDouble, (and so forth) are used. However I don't know how to port this to C#. I have tried the MemoryStream class, but there is no method to put a specific type at the end of the byte array.

Question: What is the equivalent of Java's "ByteBuffer.putType(value)" in C#? Thanks!


回答1:


You can use a BinaryWriter and your MemoryStream:

MemoryStream stream = new MemoryStream();
using (BinaryWriter writer = new BinaryWriter(stream))
{
    writer.Write(myByte);
    writer.Write(myInt32);
    writer.Write("Hello");
}

byte[] bytes = stream.ToArray();



回答2:


Try the BinaryWriter class:

using (var binaryWriter = new BinaryWriter(...))
{
    binaryWriter.Write(323);
    binaryWriter.Write(3487d);
    binaryWriter.Write("Hello");
}



回答3:


You'll be wanting to use the BitConverter class. The main difference is that these methods return an array of bytes instead of altering an existing array.

(This is a replacement for the specific methods mentioned; for a replacement of the entire ByteBuffer class, see the other replies.)



来源:https://stackoverflow.com/questions/1261543/equivalent-of-javas-bytebuffer-puttype-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!