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 slogan of progress is changing from the full dinner pail to the full garage.
    Herbert Hoover (1874–1964)

    Assemble, first, all casual bits and scraps
    That may shake down into a world perhaps;
    People this world, by chance created so,
    With random persons whom you do not know—
    Robert Graves (1895–1985)

    Swift blazing flag of the regiment,
    Eagle with crest of red and gold,
    These men were born to drill and die.
    Point for them the virtue of slaughter,
    Make plain to them the excellence of killing
    And a field where a thousand corpses lie.
    Stephen Crane (1871–1900)

    It is impossible to give a clear account of the world, but art can teach us to reproduce it—just as the world reproduces itself in the course of its eternal gyrations. The primordial sea indefatigably repeats the same words and casts up the same astonished beings on the same sea-shore.
    Albert Camus (1913–1960)