What is the equivalent of Java's ByteBuffer.wrap in C#?

10,198

Use a binary writer and a memory stream.

I have not flagged this question as a duplicate only because you didn't ask precisely what that other poster did. I am not sure what to do in that case, but still wish to help you. Good luck!

Here's the code from that link for posterity's sake:

MemoryStream stream = new MemoryStream();
using (BinaryWriter writer = new BinaryWriter(stream))
{
    writer.Write(myByte);
    writer.Write(myInt32);
    writer.Write("Hello");
}
byte[] bytes = stream.ToArray();
Share:
10,198
NoeL
Author by

NoeL

Updated on June 25, 2022

Comments

  • NoeL
    NoeL about 2 years
    byte[] input = new byte[] {2, 4, 5, 2, 1};
    ByteBuffer bytebuf = ByteBuffer.wrap(input);
    

    ByteBuffer.wrap(byte[] array) method makes buffer and array are inter-connected, modifications to the buffer will cause the array to be modified and vice versa.

    The equivalent of ByteBuffer in C# is memorystream. But I don't know how to connect memorystream with array likes ByteBuffer.wrap() method did.

    Can someone tell what is the equivalent of ByteBuffer.wrap() in C#? I have searched everywhere but could not find the answer at all.

    Thanks in advance.

  • NoeL
    NoeL almost 11 years
    hi @Morisson, the link you provided is linking back to this question. Could you fix it please?
  • NoeL
    NoeL almost 11 years
    I don't think this is a right solution. The code you gave is just for inputting array to memorystream using BinaryWriter, it is not a method to connect stream with array. Even the last code byte[] bytes = stream.ToArray(); will result an error because the stream cannot be accessed because the stream has been closed by the BinaryWriter.
  • Alexei Levenkov
    Alexei Levenkov almost 11 years
    @NoeL - care to give link (MSDN?) to prove your last statement about ToArray failing on closed/disposed MemeoryStream?
  • NoeL
    NoeL almost 11 years
    @AlexeiLevenkov, ToArray() doesn't close the stream, BinaryWriter did. I don't find any MSDN link, but there is a question here stackoverflow.com/questions/1084813/… I have tested it and BinaryWriter always close the stream
  • Alexei Levenkov
    Alexei Levenkov almost 11 years
    @NoeL I'm not sure why you dislike MSDN, but this may be useful link MemoryStream.ToArray - "Note:This method works when the MemoryStream is closed."
  • William Morrison
    William Morrison almost 11 years
    Don't know how I messed that up, fixed.