Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a binary equivalent of System.Text.StringBuilder?

Tags:

c#

.net

binary

I'm concatenating a large number of byte[] arrays in C#. If I were doing this for strings, I would use StringBuilder -- is there an equivalent class that would work for binary data in byte[] arrays?

like image 367
kdt Avatar asked May 24 '09 13:05

kdt


People also ask

What is the System string and System text StringBuilder classes?

The System. Text. StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

What is the namespace for StringBuilder in C#?

StringBuilder is located in the System. Text namespace.

What is StringBuilder in C# with example?

In c#, StringBuilder is a class that is useful to represent a mutable string of characters, and it is an object of the System. Text namespace. Like string in c#, we can use a StringBuilder to create variables to hold any text, a sequential collection of characters based on our requirements.

What is the difference between string and StringBuilder in C#?

However, whereas a string is an immutable type in C#, StringBuilder is an example of a mutable item. In C#, a StringBuilder is a mutable series of characters that can be extended to store more characters if required.


2 Answers

I don't think there is an exact equivalent, but you could get it done with a BinaryWriter:

http://msdn2.microsoft.com/en-us/library/system.io.binarywriter.aspx

MemoryStream m = new MemoryStream();
BinaryWriter writer = new BinaryWriter(m);
writer.Write(true);
writer.Write("hello");
writer.Write(12345);
writer.Flush();
return m.ToArray();
like image 156
JerSchneid Avatar answered Oct 28 '22 09:10

JerSchneid


Write them into a MemoryStream, perhaps using a StreamWriter/BinaryWriter. If endian-ness is an issue, some of the classes here might help

like image 43
spender Avatar answered Oct 28 '22 10:10

spender