简体   繁体   中英

Writeable byte stream style functionality in C#

I need to build a stream of bytes, by writing int and float / double data into it. How do I easily accomplish this in C#? I'm aware of the method to get the raw bytes of a float variable, but does C# already have a byte-stream writing system that I could easily leverage?

Reading a float value from a bytearray:

uint floatBytes = .. // read 4 float bytes from byte[] array
float floatVal = *((float*)&floatBytes);

Writing a float value into bytearray:

float floatVal = ... // read a float from the float[] array
uint floatBytes = *((uint*)&floatVal);

does C# already have a byte-stream writing system that I could easily leverage?

The .NET library has a pair of stream-decorators for this, BinaryWriter and BinaryReader.

var reader = new BinaryReader(someStream);
float f1 = reader.ReadSingle();   // Single == float
double d1 = reader.ReadDouble();
string s1 = reader.ReadString();  // the Writer issues a length-prefix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM