I have a variable declared from an enumerated type. I would like to binary OR
values from this enumeration to the variable.
type
TValues = (vValue1 = $01, vValue2 = $02);
procedure BinaryOR;
var
Value : TValues;
begin
Value := Value or vValue1;
end;
But it seems like Delphi is not happy with this, as it gives a compiler error:
E2015 Operator not applicable to this operand type
How would I go about doing this? I mean I could work with integer data types and OR
the values from the enumeration, but I would prefer if the variable is of the enumeration type.
Additional Info
There seems to be a lot of questions regarding why I would like to do this or a better explanation of the actual implementation. I did solve the problem since I posted the question.
I prefer to work with enumerated types since it constrains the implementation to a specific set of values. I have an 8bit value in a protocol that is communicated between devices. This value can hold multiple states. Each bit respresents a state. I was looking for a way to OR the values together such that I can populate the value with the required states using enumerated types.
Just using single seperate constants allows room for populating the value with values from outside the defined set. I was trying to avoid this.
I hope this makes sense.
What you are trying is not possible in this way. A variable of an enumerated type can hold only one distinct value at a time:
procedure EnumTest
type
TValues = (vValue1 = $01, vValue2 = $02);
var
Value : TValues;
begin
Value := vValue1;
Value := vValue2;
end;
If you want to save several enum values in one variable, you can use a set
as shown in the following example. But please note, that these can't be or
ed together, too! For this you need to typecast the enum values to integer
using Ord
and then use the or
operator on these values.
type
TValues = (vValue1 = $01, vValue2 = $02);
TValuesSet = set of TValues;
var
Value: TValues;
Values : TValuesSet;
i: integer;
begin
Values := [vValue1, vValue2];
//or
Include(Values, vValue1);
Include(Values, vValue2);
i := 0;
// or'ing all the values in a set
for Value in Values do
i := i or Ord(Value);
Writeln(i);
// or'ing plain enum values
i := Ord(vValue1) or Ord(vValue2);
Writeln(i);
Readln;
end.
Output:
3
3