Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an integer from three bool values as bits in C++

Tags:

c++

c

boolean

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?

like image 331
tzippy Avatar asked Jul 03 '12 12:07

tzippy


2 Answers

You might find it clearer to use bitwise operators instead of multiplication and addition:

int val = (boolVal1 << 2) | (boolVal2 << 1) | boolVal3; 
like image 99
Mark Byers Avatar answered Sep 21 '22 12:09

Mark Byers


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.

like image 35
Ivan Vergiliev Avatar answered Sep 22 '22 12:09

Ivan Vergiliev