Refactor byte array into ENUM values

1

I have a function that receives some data I have to respond with a HEX value.

public byte[] GetData(string value) 
{
   byte[] returnVal = null;

    switch(value){
       case "demo1":

            byte byte1 = (byte)((32769 & 0x000000FF));
            byte byte2 = (byte)((32769 & 0x0000FF00) >> 8);
            returnVal  = new byte[] { byte1, byte2 };

            break;
       .....
    }

    return returnVal;
}

In this example I have to response with 0x8001

I create the following code to build manually a 2 byte array with the right response.

  byte byte1 = (byte)((32769 & 0x000000FF));
  byte byte2 = (byte)((32769 & 0x0000FF00) >> 8);
  var resCmd = new byte[] { byte1, byte2 };

The response can be different depending on the value I received so I want to have a ENUM with the responses and then convert that to byte array.

For example:

public enum Commands
{
    CMD1 = 0x8001,
    CMD2 = 0x8002,
    CMD3 = 0x8003
};

How can I convert an Enum for example CMD1 to the 2 byte array that I need?

Thanks

c#
arrays
asked on Stack Overflow Oct 26, 2019 by VAAA • edited Oct 26, 2019 by ChiefTwoPencils

1 Answer

2

Use BitConverter after casting it to a 16 bit unsigned int:

    var bytes = BitConverter.GetBytes((UInt16)Commands.CMD1);
answered on Stack Overflow Oct 26, 2019 by Ian Mercer

User contributions licensed under CC BY-SA 3.0