简体   繁体   中英

C++ bitwise AND for single bits

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM