Cisco:swap bits in pair

Given a byte, write code to swap every two bits in pair.
Eg:
Input: 10 01 11 01
Output: 01 10 11 10

Comments

  1. assuming the number is of 4 bits only..
    int oddbitsmask=0x0101;
    int evenbitsmsk=0x1010;
    int ans=((number & oddbitmask)<<1) &((number&evenbitmask)<<1);

    ReplyDelete
  2. @ankit continuing with same logic for a number with 8 bits
    mask will be
    int oddbitsmask=0xAA;
    int evenbitsmsk=0x55

    ReplyDelete
  3. it should be like this:-

    ans=( ( n & oddbitmask ) << 1 ) | ( ( n & evenbitmask ) >> 1 );

    ReplyDelete
  4. @ankit please correct your answer...

    ReplyDelete
  5. @priyaranjan:
    I always encounter problems in bitwise operator.can u please give a link from where i can understand these...
    also is it neccessary that this question can be done only using bitwise operator..

    according to me,

    int swap(int a[])
    {
    for(i=0;i<=3;i++)
    {
    swap(a[2*i],a[(2*i)+1]);
    }
    return a;
    }

    ReplyDelete
  6. @sorry...

    the above code be lyk dis..

    int interchange(int a[])
    {
    for(i=0;i<=3;i++)
    {
    swap(a[2*i],a[(2*i)+1]);
    }
    return a;
    }

    ReplyDelete
  7. @kamakshi no it is not mandatory to do it using bitwise but as you must be knowing there is no intrinsic support of BOOL value in c,so we have to operate on individual bits.
    In your code you are taking an integer array,so it is not efficient.
    Try to solve many problems related to bitwise.

    ReplyDelete

Post a Comment

Popular posts from this blog