C #: copy variable to byte array

How do I copy a double, int, bool or other built-in type to a byte array in C #?

I need to do this in order to use the method FileStream.Write()

.

+1


a source to share


2 answers


BitConverter.GetBytes()

can convert primitive types to byte arrays.



+8


a source


Instead of converting each value to a byte array, you can use BinaryWriter

to write the values ​​to a file stream.

Example:



using (BinaryWriter writer = new BinaryWriter(fileStream)) {
   writer.Write(1);
   writer.Write(1.0);
   writer.Write(true);
   writer.Write("Hello");
}

      

+4


a source







All Articles