I have three bool
values that represent bits. I want to have an integer in the form
true true true = 7
false true false = 2
I have
int val = 4*boolVal1 + 2*boolVal2 + boolVal3;
Is there another way, maybe even simpler?
You might find it clearer to use bitwise operators instead of multiplication and addition:
int val = (boolVal1 << 2) | (boolVal2 << 1) | boolVal3;
Or you can use Horner's method:
int val = (((boolVal1 << 1) | boolVal2) << 1) | boolVal3.
This also makes it easier to add or remove variables from the middle of the statement without having to change all the other coefficients.
However, this might be a little less obvious to the reader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With