Flag Word - Changing Bits in Flag Words

Changing Bits in Flag Words

Writing, reading or toggling bits in flags can be done only using the OR, AND and NOT operations - operations which can be performed quickly in the processor.

To set a bit, OR the status byte with a mask byte. Any bits set in the mask byte or the status byte will be set in the result.

int setBit(int val, int bit_position) { return val | (1 << bit_position); }

To clear a bit, perform a NOT operation on the mask byte, then AND it with the status byte. The result will have the appropriate flag cleared (set to 0).

int clearBit(int val, int bit_position) { return val & ~(1 << bit_position); }

To toggle a bit, XOR the status byte and the mask byte. This will set a bit if it is cleared or clear a bit if it is set.

int toggleBit(int val, int bit_position) { return val ^ (1 << bit_position); }

Read more about this topic:  Flag Word

Famous quotes containing the words changing, bits, flag and/or words:

    The spectacle [of American politics] resembles that of swarms of insects changing from worms to wings. They must get the wings or die. For our salvation, Mr. Wilbur Wright is providing wings. He will also have to provide a new insect to use them.
    Henry Brooks Adams (1838–1918)

    On their slag heap, these children
    Wear skins peeped through by bones and spectacles of steel
    With mended glass, like bottle bits in slag.
    Stephen Spender (1909–1995)

    Our flag is red, white and blue, but our nation is a rainbow—red, yellow, brown, black and white—and we’re all precious in God’s sight.
    Jesse Jackson (b. 1941)

    The dog barks, the caravan passes on.
    The words had a sort of bloom on them
    But were weightless, carrying past what was being said.
    John Ashbery (b. 1927)