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?
StringBuilder data = new StringBuilder(); for (int i = 0; i < bytes1; i++) { data. Append("a"); } byte[] buffer = Encoding. ASCII. GetBytes(data.
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
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With