Bit Manipulation - Bit Manipulation in The C Programming Language

Bit Manipulation in The C Programming Language

C has direct support for bitwise operations that can be used for bit manipulation. In the following examples, n is the index of the bit to be manipulated within the variable bit_fld, which is an unsigned char being used as a bit field. Bit indexing begins at 0, not 1. Bit 0 is the least significant bit.

Set a bit
bit_fld |= (1 << n)
Clear a bit
bit_fld &= ~(1 << n)
Toggle a bit
bit_fld ^= (1 << n)
Test a bit
bit_fld & (1 << n)

When using an array of bytes to represent set of bits, i.e., a bit array or bitset, the index of the byte in the array associated with a bit n can be calculated using division:

n / CHAR_BIT

where n is the index of the given bit and CHAR_BIT gives the number of bits in a C char.

The index of the bit within the byte indexed by the above can be calculated via a modulo operation:

n % CHAR_BIT

(Note: unsigned char is typically used in C to represent a byte and CHAR_BIT is most often 8 on modern processors. % is the C modulo operator.)

Read more about this topic:  Bit Manipulation

Famous quotes containing the words bit, manipulation, programming and/or language:

    Henry David Thoreau, who never earned much of a living or sustained a relationship with any woman that wasn’t brotherly—who lived mostly under his parents’ roof ... who advocated one day’s work and six days “off” as the weekly round and was considered a bit of a fool in his hometown ... is probably the American writer who tells us best how to live comfortably with our most constant companion, ourselves.
    Edward Hoagland (b. 1932)

    Denotation by means of sounds and markings is a remarkable abstraction. Three letters designate God for me; several lines a million things. How easy becomes the manipulation of the universe here, how evident the concentration of the intellectual world! Language is the dynamics of the spiritual realm. One word of command moves armies; the word liberty entire nations.
    Novalis [Friedrich Von Hardenberg] (1772–1801)

    If there is a price to pay for the privilege of spending the early years of child rearing in the driver’s seat, it is our reluctance, our inability, to tolerate being demoted to the backseat. Spurred by our success in programming our children during the preschool years, we may find it difficult to forgo in later states the level of control that once afforded us so much satisfaction.
    Melinda M. Marshall (20th century)

    Talking about dreams is like talking about movies, since the cinema uses the language of dreams; years can pass in a second and you can hop from one place to another. It’s a language made of image. And in the real cinema, every object and every light means something, as in a dream.
    Frederico Fellini (1920–1993)