views:

378

answers:

3

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).

+2  A: 

You can use the BitConverter.GetBytes method to do this.

Sean
+4  A: 

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);
Jørn Schou-Rode
still need to cast it, but it's better. thanks!
Nefzen
If primitive types are not enough, see my answer for how to convert any value type.
OregonGhost
+3  A: 

To convert any value types (not just primitive types) to byte arrays and vice versa:

    public T FromByteArray<T>(byte[] rawValue)
    {
        GCHandle handle = GCHandle.Alloc(rawValue, GCHandleType.Pinned);
        T structure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
        handle.Free();
        return structure;
    }

    public byte[] ToByteArray(object value, int maxLength)
    {
        int rawsize = Marshal.SizeOf(value);
        byte[] rawdata = new byte[rawsize];
        GCHandle handle =
            GCHandle.Alloc(rawdata,
            GCHandleType.Pinned);
        Marshal.StructureToPtr(value,
            handle.AddrOfPinnedObject(),
            false);
        handle.Free();
        if (maxLength < rawdata.Length) {
            byte[] temp = new byte[maxLength];
            Array.Copy(rawdata, temp, maxLength);
            return temp;
        } else {
            return rawdata;
        }
    }
OregonGhost