C - Bits Manipulation
| Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a byte. C language is very efficient in manipulating bits. Here are following operators to perform bits manipulation: Bitwise Operators:Bitwise operator works on bits and perform bit by bit operation.Assume if B = 60; and B = 13; Now in binary format they will be as follows: A = 0011 1100 B = 0000 1101 ----------------- A&B = 0000 1000 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011 Show Examples There are following Bitwise operators supported by C language
For example: x << 2 shifts the bits in x by 2 places to the left.
To illustrate many points of bitwise operators let us write a function, Bitcount, that counts bits set to 1 in an 8 bit number (unsigned char) passed as an argument to the function.
Bit FieldsBit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium. Typical examples:
C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case then some compilers may allow memory overlap for the fields whilst other would store the next field in the next word. |
Comments
Post a Comment