Given
enum
{
VAL1,
VAL2,
VAL3,
VAL4
};
results in VAL1 = 0, VAL2 = 1, VAL3 = 2, VAL4 = 3.
What enum would create binary incremental values?
VAL1 = 1, VAL2 = 2, VAL3 = 4, VAL4 = 8
This thread has been locked.
If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.
You can simply use the following:
enum binary_enum
{
VAL1 = 1,
VAL2 = 2,
VAL3 = 4,
VAL4 = 8
};
Clyde Eisenbeis said:Is there an enum that does this automatically?
No. An alternative might be to use a macro. Something like:
#define BIT(x) (1<<x)
In general we find deviation from ANSI C makes a lot of developers very unhappy.
I don't understand. What do you want to do that this code snippet does not do?
#define POW2(n) (1 << (n)) // Might need to write 1L << (n)
enum binary_vals {
VAL1 = POW2(0),
VAL2 = POW2(1),
VAL3 = POW2(2),
VAL4 = POW2(3)
};
If you can code it up in reasonable fashion like that, then I don't see any reason to add something to the language.
Thanks and regards,
-George
enum_binary {
STATUS_SENSOR_FAILURE,
STATUS_MIRROR_DUPLICATION,
STATUS_FLASH_FAILURE,
STATUS_COUNT_EXCEEDED
};
The end result would be: STATUS_SENSOR_FAILURE = 1 ... STATUS_MIRROR_DUPLICATION = 2 ... STATUS_FLASH_FAILURE = 4 ... STATUS_COUNT_EXCEEDED = 8.
By logical or'ing a status variable using this enum when errors occur (for example: uiStatus |= STATUS_FLASH_FAILURE, then later uiStatus |= STATUS_SENSOR_FAILURE), it would be easy to extract the problems when the status variable is examined.
It is very easy to code that up yourself. Thus, IMHO, your suggestion for a language extension is not very compelling.
Thanks and regards,
-George
Yes, it can be created using #defines. But when the status variable is of type 'long', that is a lot of numbers to enter ... and it is easy to make a mistake with that many digits. With an enum_binary type function, it would make this very simple.
IMHO, it is quite compelling. Try it. Write some code implementing the binary aspect for a 'long' variable using #defines. Be sure to define all 32 bits.
What is the procedure for contacting the ANSI group that defines C code standards?
Extending the C language means that we are NOT compatible with any other compiler. In other words, if we implement that feature and you use it, then you would be unable to compile your code with any other compiler in the world. We're happy to have you use only TI compilers, but most of our customers react negatively to that sort of a feature. I don't think breaking compatibility with every other C compiler is justified in order to save you from writing 32 lines of code.
Clyde Eisenbeis said:What is the procedure for contacting the ANSI group that defines C code standards?
I don't know the details. Their web site is http://www.open-std.org/jtc1/sc22/wg14/ .
Thanks and regards,
-George