Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 863
Lazlo Avatar asked Dec 10 '22 19:12

Lazlo


2 Answers

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();
like image 96
user7116 Avatar answered Dec 25 '22 23:12

user7116


Try the BinaryWriter class:

using (var binaryWriter = new BinaryWriter(...))
{
    binaryWriter.Write(323);
    binaryWriter.Write(3487d);
    binaryWriter.Write("Hello");
}
like image 40
Kent Boogaart Avatar answered Dec 26 '22 00:12

Kent Boogaart