1

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.

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

3 Comments

Yes and for strings you would need to use GetBytes on your encoding object.
Why people keeps voting this answer? The question is about copying primitive types to a byte array, not converting them.
@Trap, How would you copy a non-byte type's value to a byte array without converting?
4

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");
}

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.