Wednesday, 22 January 2014

Bitwise Operators in C

BITWISE OPERATORS:

    Bitwise operators are u.d to manipulate one or more bits from integral operands like char, int, short, long.

    C language supports the following bitwise operators.

        | – Bitwise OR
   
    & – Bitwise AND

        ~ – One’s complement
   
    ^ – Bitwise XOR
   
    << – left shift
   
    >> – right shift

Note on shifting signed and unsigned numbers:

While performing shifting, if the operand is a signed value, then arithmetic shift will be used. If the type is unsigned, then logical shift will be used.

In case of arithmetic shift, the sign-bit ( MSB ) is preserved. Logical shift will not preserve the signed bit. Let’s see this via an example.

#include<stdio.h>

int main()
   
    {
        signed char a=-8;
         signed char b= a >> 1;
         printf("%d\n",b);
    }

In the above code, we are right shifting -8 by 1. The result will be “-4". Here arithmetic shift is applied since the operand is a signed value.

#include<stdio.h>

int main()
   
    {
         unsigned char a=-8;
        unsigned char b= a >> 1;
        printf("%d\n",b);
     }

 Negative number are represented using 2's complement of its positive equivalent.

2's compliment of +8 is

1111 1000

Right shifting by 1 yields,

0111 1100 ( 124 in decimal )

The above code will result in 124 ( Positive value ). Here logical shift is applied since the operand is unsigned, and it won’t preserve the MSB of the operand.

Right shifts preserve the sign bit. When a signed integer shifts right, the most-significant bit remains set. When an unsigned integer shifts right, the most-significant bit is cleared.

No comments: