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 human condition is such that pain and effort are not just symptoms which can be removed without changing life itself; they are the modes in which life itself, together with the necessity to which it is bound, makes itself felt. For mortals, the “easy life of the gods” would be a lifeless life.”
    —Hannah Arendt (1906–1975)

    “Many bits of fox fur will make a fine robe.”
    —Chinese proverb.

    “—Here, the flag snaps in the glare and silence
    Of the unbroken ice. I stand here,
    The dogs bark, my beard is black, and I stare
    At the North Pole. . .
    And now what? Why, go back.

    Turn as I please, my step is to the south.”
    —Randall Jarrell (1914–1965)

    “Hear, O Israel: The LORD is our God, the LORD alone; You shall love the LORD your God with all your heart, and with all your soul, and with all your might. Keep these words that I am commanding you today in your heart. Recite them to your children and talk about them when you are at home and when you are away, when you lie down and when you rise. Bind them as a sign on your hand, fix them as an emblem on your forehead, and write them on the doorposts of your house and on your gates.”
    —Bible: Hebrew, Deuteronomy 6:4-9.