Question

I've got just a simple question about bitwise AND in C++. I'm using it for single bits (a&8, a&4, a&2, a&1, etc.) and I want to get bool value as a return (if there's 1 on the position).

I may divide it by a number (like (a&8)/8), but it dosn't really look nice in my code (especially, that I'm using arrays and long names of variables).

Is there any other, better, way to code it?

Thanks in advance.

Was it helpful?

Solution

The best way is to convert the expression to a boolean value. This improves readability:

bool result;
result = 0 != (a & 8);

The comparison with 0 might be unnecessary since the compiled code will write true or false in the variable b. But this avoids a warning like:

warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)

The order or the comparison argument might be reversed if you don't like Yoda speech. It's a style that can help avoid accidental assignments in C programming language.

OTHER TIPS

If you want to be explicit, compare with 0:

const bool maskSet = (a & 8) != 0;

That's the cleanest way I know of. Dividing is much stranger, since that still leaves the conversion from an integer to a boolean implicit. The comparison operator makes it explicit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top