Nefzen Nefzen - 1 month ago 12
C# Question

how to convert a value type to byte[] in C#?

I want to do the equivalent of this:

byte[] byteArray;
enum commands : byte {one, two};
commands content = one;
byteArray = (byte*)&content;


yes, it's a byte now, but consider I want to change it in the future? how do I make byteArray contain content? (I don't care to copy it).

Answer

The BitConverter class might be what you are looking for. Example:

int input = 123;
byte[] output = BitConverter.GetBytes(input);

If your enum was known to be an Int32 derived type, you could simply cast its values first:

BitConverter.GetBytes((int)commands.one);