Search code examples
c#javamemorystreambytebuffer

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


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.


Solution

  • 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();