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

前端 未结 5 1937
南旧
南旧 2020-12-11 16:36

I want to do the equivalent of this:

byte[] byteArray;
enum commands : byte {one, two};
commands content = one;
byteArray = (byte*)&content;
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 17:02

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

提交回复
热议问题