Fastest way to convert from/to byte array
-
I need to convert various datatypes (mostly doubles, bytes and strings) to byte array and then read it back. I need to read it the fastest way possible and it will be read thousands of times and written only once. What I use now is BinaryReader/Writer like so: MemoryStream stream = new MemoryStream() BinaryWriter writer = new BinaryWriter(stream) .. loop .. writer.write(byte) writer.write(double) writer.write(string) ... return stream.ToArray(); I don't care how fast writing is. Then I need to read the data: byte[] data = ... MemoryStream stream = new MemoryStream(data); BinaryReader reader = new BinaryReader(stream); while (stream.Position < stream.Length) { byte b = reader.ReadByte(); switch (b) { // depending on value of b read strings, doubles or bytes } } This approach doesn't seem to be too fast. I'm wondering if there is a faster way to do that. Thanks.
-
I need to convert various datatypes (mostly doubles, bytes and strings) to byte array and then read it back. I need to read it the fastest way possible and it will be read thousands of times and written only once. What I use now is BinaryReader/Writer like so: MemoryStream stream = new MemoryStream() BinaryWriter writer = new BinaryWriter(stream) .. loop .. writer.write(byte) writer.write(double) writer.write(string) ... return stream.ToArray(); I don't care how fast writing is. Then I need to read the data: byte[] data = ... MemoryStream stream = new MemoryStream(data); BinaryReader reader = new BinaryReader(stream); while (stream.Position < stream.Length) { byte b = reader.ReadByte(); switch (b) { // depending on value of b read strings, doubles or bytes } } This approach doesn't seem to be too fast. I'm wondering if there is a faster way to do that. Thanks.
See the
BitConverter
class documentation in the .NET Framework SDK.Microsoft MVP, Visual C# My Articles