How do I check a byte representation to an enumeration member in python?

Question:

In C# I can check a byte representation to an enum number like this:

using System;

namespace HelloWorld {
    class Hello {
        public enum Types {
            NONE = 0x01,
            TRUE = 0x02,
            FALSE = 0x03,
            STRING_8 = 0x30
        };
        
        static void Main() {
            // 3 would be the byte number -> FALSE
            // 48 would be the byte number -> STRING_8
            Console.WriteLine((Types)Enum.ToObject(typeof(Types), 3));
            Console.WriteLine((Types)Enum.ToObject(typeof(Types), 48));
        }
    }
}

How can I replicate this in Python? I don’t know what function to look for to make this work, I need this to parse binary files in Python that contain json data.

I looked up on google and found out enumeration classes do exist in Python, but couldn’t find a function that fits & answers my problem.

Asked By: SkinnyMamba

||

Answers:

In Python, you can use the int.from_bytes function to convert a byte representation to an integer, and then use the int function to cast the integer to the corresponding enum value.

Here’s an example of how you can do this in Python:

from enum import Enum

class Types(Enum):
    NONE = 0x01
    TRUE = 0x02
    FALSE = 0x03
    STRING_8 = 0x30

# Convert a byte representation to an integer
byte_representation = b'x03'
int_value = int.from_bytes(byte_representation, 'little')

# Cast the integer to the corresponding enum value
enum_value = Types(int_value)

print(enum_value)  # Output: Types.FALSE

Note that the int.from_bytes function takes an optional byteorder argument, which specifies the endianness of the byte representation. In the example above, we use the ‘little’ byteorder, which means that the byte representation is in little-endian format. You can use the ‘big’ byteorder if the byte representation is in big-endian format.

You can also use the enum.IntEnum class to define enums that have integer values, which allows you to cast integers directly to enum values without the need to use the int function:

from enum import IntEnum

class Types(IntEnum):
    NONE = 0x01
    TRUE = 0x02
    FALSE = 0x03
    STRING_8 = 0x30

# Convert a byte representation to an integer
byte_representation = b'x03'
int_value = int.from_bytes(byte_representation, 'little')

# Cast the integer directly to the corresponding enum value
enum_value = Types(int_value)

print(enum_value)  # Output: Types.FALSE
Answered By: Dmytro Leonenko
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.