Bit Manipulation

Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word.

Tasks that require bit manipulation:

  • Low-level device control.

  • Error detection.

  • Correction algorithms.

  • Data compression.

  • Encryption.

  • Algorithms optimization.

Binary numbers system

Each position value in a binary number are the powers of two:

 128      64      32        16          8           4         2       1
 2^7     2^6     2^5        2^4        2^3         2^2        2^1    2^0

1 byte = 8 bits.

0 = off, 1 = on.

The rightmost bit of a byte is known as the least significant or low-order bit, the leftmost bit is known as the most significant or high-order bit.

Changing a bit to 1 is called setting a bit changing a bit to 0 is called resetting a bit.

Bits for basic C data types

Negative numbers (signed)

The representation of negative number:

A way to convert negative numbers from decimal to binary is to first add 1 to the value express the absolute value of the result in binary complement all the bits change all the 1s to 0s and 0s to 1s.

Example:

Example:

Example:

Including math.h brings in the declaration of the various functions and not their definition.

You need to link your program with this library so that the calls to functions like pow() are resolved.