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:

    Loves riddles are, that though thy heart depart,
    It stayes at home, and thou with losing savest it:
    But wee will have a way more liberall,
    Then changing hearts, to joyne them, so wee shall
    Be one, and one anothers All.
    John Donne (1572–1631)

    At death, you break up: the bits that were you
    Start speeding away from each other for ever
    With no one to see.
    Philip Larkin (1922–1986)

    Hath not the morning dawned with added light?
    And shall not evening call another star
    Out of the infinite regions of the night,
    To mark this day in Heaven? At last, we are
    A nation among nations; and the world
    Shall soon behold in many a distant port
    Another flag unfurled!
    Henry Timrod (1828–1867)

    Of all the words mentioned in language, there is not one that I hate more than the word “right.” Is it your right that your field prospers? That you don’t drop dead this very instant? Are living and breathing your right? As far as I can see, nothing but grace and blessing fill the universe, and these worms talk about right?
    Franz Grillparzer (1791–1872)