0

Declare enum as hex.
I want to compare this enum to the value of a byte array.

An enum declared in hex.

enum ByteArrayType
{
    None = 0x0000,

    OK = 0x4F4B,
    NK = 0x4E4B,
}

my thoughts
byte[] byteOri = { 0x4F, 0x4B };
ByteArrayType typeSelect = ByteArrayType.OK;


//Exception
typeSelect == (ByteArrayType)byteOri

//False
(short)typeSelect == BitConverter.ToInt16(byteOri)

//False
byteOri.Equals(BitConverter.GetBytes((short)typeSelect))


I found the 'string -> cast' method.

How can I cast int to enum?

(ByteArrayType)Enum.Parse(typeof(ByteArrayType), ASCIIEncoding.Default.GetString(byteOri));


but the way i want
It's not a way to turn it into a string.

Is there any other way?


The full test code is here.

  • What version of .NET? Modern versions support things like `BinaryPrimitives`, so you can write `BinaryPrimitives.WriteUInt16BigEndian(buffer, (UInt16) ByteArrayType.OK)` and `(ByteArrayType) BinaryPrimitives.ReadUInt16BigEndian(byteOri)` (having `Span` available for such work also improves performance quite a bit). Manually dealing with endianness is tedious. – Jeroen Mostert Mar 05 '22 at 11:56
  • @JeroenMostert Thanks for the reply. `(ByteArrayType)BinaryPrimitives.ReadUInt16BigEndian(byteOri)` works what you want. Added to test code. – Dang-gun Roleeyas Mar 05 '22 at 15:36

0 Answers0