Saturday, 12 May 2018

Bitwise Operator


Bit Operator


| – Bitwise OR
& – Bitwise AND
~ – One’s complement
^ – Bitwise XOR
<< – left shift
>> – right shift


Bitwise OR – |


   1010
   1100
   -------
OR 1110 
   -------
 

Bitwise AND – &


    1010
    1100
    -------
AND 1000   
    -------


One’s Complement operator – ~


       1001
NOT
      -------
       0110
      -------

 

Bitwise XOR – ^


     0101
     0110
     ------
XOR  0011
     ------


 

Left shift Operator – <<

int a=2<<1;

Position  7    6    5    4    3    2    1    0
Bits      0    0    0    0    0    0    1    0

after 1 time shift:

Position  7    6    5    4    3    2    1    0
Bits      0    0    0    0    0    1    0    0

 

Right shift Operator – >>

========================

int a=8>>1;

Position    7    6    5    4    3    2    1    0
Bits        0    0    0    0    1    0    0    0


after 1 right shift:

Position   7    6    5    4    3    2    1    0
Bits      0     0    0    0    0    1    0    0

 

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.


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.




Now unsigned shift:

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


Note: Negative number are represented using 2’s complement of its positive equivalent.


2's compliment of +8 is
          8 = 0000 1000
1st complit = 1111 0111
2's compli  = 1111 1000

1111 1000

Right shifting by 1 yields, 0111 1100 ( 124 in decimal )

Hence we will get the positive 124 value:


 

Toggle a bit:

============
value = data ^ (1 << n)

Input data is 8
Bit needs to be toggled is 2.

   value = (0000 1000) ^ (0000 0001 << 2)
         = (0000 1000) ^ (0000 0100) => (0000 1100) = 12




 

Tricks:

********

Get the maximum integer

int maxInt = ~(1 << 31);
int maxInt = (1 << 31) - 1;
int maxInt = (1 << -1) - 1;

 

Get the minimum integer

int minInt = 1 << 31;
int minInt = 1 << -1;

 

Get the maximum long

long maxLong = ((long)1 << 127) - 1;

 

Multiplied by 2

n << 1; // n*2

 

Divided by 2

n >> 1; // n/2

 

Multiplied by the m-th power of 2

n << m;

 

Divided by the m-th power of 2

n >> m;

 

Check odd number

(n & 1) == 1;


Exchange two values

a ^= b;
b ^= a;
a ^= b;

No comments:

Post a Comment