Frage

I've read other questions about this, but they don't answer my question.

In the following code I understand that it checks if that bit is set, but my question is why?

bool test(uint8_t& flag)
{
   return flag & (1 << 4);
}

I don't get why it returns a bool and it works, flag is uint8_t and 1 << 4 should be something like this 00010000 (I think). Why does that code return the value of the desired single bit and not the rightmost or something like that?

War es hilfreich?

Lösung

The C++ draft standard section 4.12 Boolean conversions says (emphasis mine):

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

So any non-zero value will be converted to true.

You expressed some doubts as to the result of 1 << 4 we have a quick way to check this using std::bitset:

#include <bitset>
#include <iostream>

int main() 
{
    std::bitset<8> b1(1<<4);

    std::cout << b1 << std::endl ;

    return 0;
}

and we can see the result is indeed 00010000 since bitwise and only set a bit to 1 if the bit in both operands are 1 then the result of flag & (1 << 4) will only be non-zero if bit 5 of flag is also 1.

Andere Tipps

An int can be converted to a bool. If its value is zero, the converted value ist false, otherwise it is true. Check it out yorself:

bool f = 0;
bool t = 5;

Prvalues of integral, floating-point, unscoped enumeration, pointer, and pointer-to-member types can be converted to prvalues of type bool.

The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other values become true.

See: cppreference

The & operator performs a bitwise boolean AND operation. That means that a bit is set in the final output if, and only if, it is set in both inputs, so for example

  00011100
& 01010101
  --------
= 00010100

  11010101
& 01010101
  --------
= 01010101

So, if you use a mask that has only a single bit set it will return 0 if that bit is not set, and non-zero if it is set, e.g.

  11110111
& 00001000
  --------
= 00000000

  00001111
& 00001000
  --------
= 00001000

Then, since C++ will convert treat any non-zero value as true when converting to a bool and zero as false the function works.

Since this is also tagged C, C99 has this to say:

6.3.1.2 Boolean type

1 When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top