Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting enum definition to unsigned int

According to this SO post:
What is the size of an enum in C?
enum types have signed int type.

I would like to convert an enum definition from signed int to unsigned int.

For example, on my platform an unsigned int is 32-bits wide. I want to create an enum:

typedef enum hardware_register_e
{
    REGISTER_STATUS_BIT = (1U << 31U)
} My_Register_Bits_t;

My compiler is complaining that the above definition is out of range (which it is for a signed int).

How do I declare unsigned int enum values?

Edit 1:

  1. The preference is not to expand to 64 bits (because the code resides in an embedded system).
  2. Due to skill limitations, C++ is not allowed for this project. :-(

Edit 2:

  • Compiler is IAR Embedded Workbench for ARM7.
like image 534
Thomas Matthews Avatar asked Jul 03 '12 15:07

Thomas Matthews


People also ask

Can you cast an enum to an int?

Overview. To convert an enum to int , we can: Typecast the enum value to int . Use the ToInt32 method of the Convert class.

Is an enum an unsigned int?

An enum type is represented by an underlying integer type. The size of the integer type and whether it is signed is based on the range of values of the enumerated constants. In strict C89 or C99 mode, the compiler allows only enumeration constants with values that will fit in "int" or "unsigned int" (32 bits).

Can you cast an enum?

Enum's in . Net are integral types and therefore any valid integral value can be cast to an Enum type. This is still possible even when the value being cast is outside of the values defined for the given enumeration!

How do you create an unsigned enum?

You can either solve this by adding an explicit cast to the "underlying type" (intended type), in this case a cast to uint8_t. Or you can solve it by never using enums at all, replace them with #defines.


1 Answers

According to this SO post: What is the size of an enum in C? enum types have signed int type.

The thing is enum types can be int type but they are not int in C. On gcc 1), enum types are unsigned int by default.

enum constants are int but enum types are implementation defined.

In your case the enum constant is int but you are giving it a value that does not fit in a int. You cannot have unsigned int enum constants in C as C says they are int.


1) gcc implementation defined enum type documentation: "Normally, the type is unsigned int if there are no negative values in the enumeration, otherwise int" in http://gcc.gnu.org/onlinedocs/gcc/Structures-unions-enumerations-and-bit_002dfields-implementation.html

like image 112
ouah Avatar answered Sep 24 '22 21:09

ouah