Use expression evaluation of x & 01 to control if This function illustrates many C program points:įor loop not used for simple counting operation.įor loop will repeatedly shift right x until x becomes 0
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. So if you want fast multiplications or division by 2 use shifts. Shifting is much faster than actual multiplication (*) or division (/) by 2. Similarly a shift right is equal to division by 2. Therefore a shift left is equivalent to a multiplication by 2. The vacated bits are filled with zero.įor example: x >= 2 => x = 00000000 or just 0 (decimal)Īlso: if x = 00000010 (binary) or 2 (decimal) The shift operators perform appropriate shift by operator on the right to the operator on the left. The left operands value is moved right by the number of bits specified by the right operand. There are following Bitwise operators supported by C language Operatorīinary AND Operator copies a bit to the result if it exists in both operands.īinary OR Operator copies a bit if it exists in eather operand.īinary XOR Operator copies the bit if it is set in one operand but not both.īinary Ones Complement Operator is unary and has the efect of 'flipping' bits.īinary Right Shift Operator.
Here are following operators to perform bits manipulation: Bitwise Operators:īitwise operator works on bits and perform bit by bit operation.Īssume if B = 60 and B = 13 Now in binary format they will be as follows: C language is very efficient in manipulating bits. Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a byte.