Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of StringBuilder for byte arrays

This is a simple one, and one that I thought would have been answered. I did try to find an answer on here, but didn't come up with anything - so apologies if there is something I have missed.

Anyway, is there an equivalent of StringBuilder but for byte arrays?

I'm not bothered about all the different overloads of Append() - but I'd like to see Append(byte) and Append(byte[]).

Is there anything around or is it roll-your-own time?

like image 332
Matt Whitfield Avatar asked Oct 25 '10 14:10

Matt Whitfield


People also ask

How to convert StringBuilder to bytes?

StringBuilder data = new StringBuilder(); for (int i = 0; i < bytes1; i++) { data. Append("a"); } byte[] buffer = Encoding. ASCII. GetBytes(data.


2 Answers

Would MemoryStream work for you? The interface might not be quite as convenient, but it offers a simple way to append bytes, and when you are done you can get the contents as a byte[] by calling ToArray().

A more StringBuilder-like interface could probably be achieved by making an extension method.

Update
Extension methods could look like this:

public static class MemoryStreamExtensions {     public static void Append(this MemoryStream stream, byte value)     {         stream.Append(new[] { value });     }      public static void Append(this MemoryStream stream, byte[] values)     {         stream.Write(values, 0, values.Length);     } } 

Usage:

MemoryStream stream = new MemoryStream(); stream.Append(67); stream.Append(new byte[] { 68, 69 }); byte[] data = stream.ToArray();  // gets an array with bytes 67, 68 and 69 
like image 63
Fredrik Mörk Avatar answered Sep 21 '22 13:09

Fredrik Mörk


The MemoryStream approach is good, but if you want to have StringBuilder-like behavior add a BinaryWriter. BinaryWriter provides all the Write overrides you could want.

MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); writer.Write((byte)67); writer.Write(new byte[] { 68, 69 }); 
like image 35
Tergiver Avatar answered Sep 17 '22 13:09

Tergiver