Friday 16 December 2011

Bit pattern - Circular Right Shift

Yesterday's exam question
didn't get it during the exam though...was completely out of time.

void circularShiftRight(unsigned& V, int fromBit, int toBit, int times) {
  unsigned int tempV = V;
  unsigned int rightBit = 0;
  unsigned int mask = 0;
  bool checkRightBit;
  int i,j;
  for (j = 0;j < times;j++) {
    checkRightBit = !!(V & (1 << fromBit - 1));
    rightBit = checkRightBit?(1<<toBit - 1):0;

    mask = 0;
    for (i = fromBit;i < toBit + 1;i++)
      mask = mask | (1 << (i-1));

    tempV = tempV & mask;
    tempV = tempV >> fromBit;
    tempV = tempV << (fromBit - 1);
    tempV = tempV | rightBit;
    V = V & ~mask;
    V = tempV | V;
  }
}

void prnBits(unsigned int Val){
  for(int i= sizeof(Val)*8;i>0;i--){
    if(!(i%4)) printf(" ");
    printf("%d", IsSet(Val,i)?1:0);
  }
  printf("\n");
}

int main(){
  unsigned int B = 0xABCDEF11;
  unsigned int C;
  prnBits(B);
  circularShiftRight(B, 5, 12, 4);
  prnBits(B);
  circularShiftRight(B, 5, 12, 4);
  prnBits(B);
  return 0;
}

//Output
 1010 1011 1100 1101 1110 1111 0001 0001
 1010 1011 1100 1101 1110 0001 1111 0001
 1010 1011 1100 1101 1110 1111 0001 0001
Press any key to continue . . .

No comments:

Post a Comment