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:

    Good mothers know that their relationship with each of their children is like a movable feast, constantly changing and evolving.
    Sue Woodman (20th century)

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

    By the rude bridge that arched the flood,
    Their flag to April’s breeze unfurled,
    Here once the embattled farmers stood
    And fired the shot heard round the world.
    Ralph Waldo Emerson (1803–1882)

    I am filling the room
    with the words from my pen.
    Words leak out of it like a miscarriage.
    I am zinging words out into the air
    and they come back like squash balls.
    Yet there is silence.
    Anne Sexton (1928–1974)