1

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.

2
  • 4
    bool bTrue = (a & 8); should be good enough or even bool bTrue = (a & 8) != 0;. Commented May 5, 2014 at 9:38
  • What is the problem? What you have should valuate to true or false in the right context without dividing or any other manipulations. Commented May 5, 2014 at 9:38

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Samik Note that bool result = a & 8; would do fine. Personally I find overly verbose versions confusing. And the back to front Yoda style even more so :-)
Ye, I do know that :) Still, I've got to use these as index in array so it's like array[(a&8) != 0]. I hope that's the best solution.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.