2

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);
0

2 Answers 2

4

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.
Sign up to request clarification or add additional context in comments.

Comments

1

Use BinaryReader and BinaryWriter

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.