Java equivalent of "ByteBuffer.putType ()" in C #

I am trying to format a byte array in C # by porting code from Java. Java uses the methods "buf.putInt (value);", buf.putShort, buf.putDouble, (etc.). However, I do not know how to port this to C #. I tried the MemoryStream class, but there is no way to put a specific type at the end of a byte array.

Question: What is the Java equivalent of โ€œByteBuffer.putType (value)โ€ in C #? Thanks!

+2
source share
3 answers

You can use 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(); 
+7
source

Try the BinaryWriter class:

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

You will want to use the BitConverter class. The main difference is that these methods return an array of bytes instead of modifying the existing array.

(This is a replacement for the specific methods mentioned; to replace the entire ByteBuffer class, see other answers.)

0
source

Source: https://habr.com/ru/post/1495170/


All Articles