views:

689

answers:

2

Hi

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

I need to do it to use the FileStream.Write() method.

+7  A: 

BitConverter.GetBytes() can convert primitive types to byte arrays.

Anton Gogolev
Yes and for strings you would need to use GetBytes on your encoding object.
Galilyou
Why people keeps voting this answer? The question is about copying primitive types to a byte array, not converting them.
Trap
+4  A: 

Instead of converting each value to a byte array, you can use a BinaryWriter to write the values to the file stream.

Example:

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