Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Enum to Binary (via Integer or something similar)

Tags:

enums

binary

ada

I have an Ada enum with 2 values type Polarity is (Normal, Reversed), and I would like to convert them to 0, 1 (or True, False--as Boolean seems to implicitly play nice as binary) respectively, so I can store their values as specific bits in a byte. How can I accomplish this?

like image 810
weberc2 Avatar asked Dec 04 '12 01:12

weberc2


2 Answers

An easy way is a lookup table:

Bool_Polarity : constant Array(Polarity) of Boolean 
              := (Normal=>False, Reversed => True);

then use it as

 B Boolean := Bool_Polarity(P);

Of course there is nothing wrong with using the 'Pos attribute, but the LUT makes the mapping readable and very obvious.

As it is constant, you'd like to hope it optimises away during the constant folding stage, and it seems to: I have used similar tricks compiling for AVR with very acceptable executable sizes (down to 0.6k to independently drive 2 stepper motors)

like image 140
user_1818839 Avatar answered Sep 30 '22 14:09

user_1818839


3.5.5 Operations of Discrete Types include the function S'Pos(Arg : S'Base), which "returns the position number of the value of Arg, as a value of type universal integer." Hence,

Polarity'Pos(Normal) = 0
Polarity'Pos(Reversed) = 1

You can change the numbering using 13.4 Enumeration Representation Clauses.

...and, of course:

Boolean'Val(Polarity'Pos(Normal)) = False
Boolean'Val(Polarity'Pos(Reversed)) = True
like image 42
trashgod Avatar answered Sep 30 '22 15:09

trashgod