4

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!

Lazlo
  • 8,518
  • 14
  • 77
  • 116

3 Answers3

9

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();
user7116
  • 63,008
  • 17
  • 141
  • 172
5

Try the BinaryWriter class:

using (var binaryWriter = new BinaryWriter(...))
{
    binaryWriter.Write(323);
    binaryWriter.Write(3487d);
    binaryWriter.Write("Hello");
}
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • 1
    We both enjoy writing 3 things, including Hello. – user7116 Aug 11 '09 at 16:45
  • Thank you for this, it's exactly what I was looking for :). However, how can I get back to a byte array after using the binary writer? – Lazlo Aug 11 '09 at 17:00
  • If the binary writer is wrapped around a `MemoryStream`, you can call `ToArray` on it and get a byte array. – John Calsbeek Aug 11 '09 at 17:04
  • I feel completely stupid asking another question, but, how do I wrap it around a MemoryStream? – Lazlo Aug 11 '09 at 17:17
  • Lazlo, you can see my answer for how you "wrap it around a memory stream" (I don't feel its my place to edit Kent's). – user7116 Aug 11 '09 at 18:10
0

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.)

John Calsbeek
  • 35,947
  • 7
  • 94
  • 101