Showing posts with label swap. Show all posts
Showing posts with label swap. Show all posts

Saturday, December 5, 2009

To swap the two nibbles in a byte

#include 

unsigned char swap_nibbles(unsigned char c)
{
  unsigned char temp1, temp2;
  temp1 = c & 0x0F;
  temp2 = c & 0xF0;
  temp1=temp1 << 4;
  temp2=temp2 >> 4;

  return(temp2|temp1); //adding the bits
}

int main(void)
{
  char ch=0x34;
  printf("\nThe exchanged value is %x",swap_nibbles(ch));
  return 0;
}

Thursday, November 26, 2009

Swapping 2 variables using macro

 #define swap(type,a,b) type temp;temp=a;a=b;b=temp;

Now, think what happens if you pass in something like this


swap(int,temp,a) //You have a variable called "temp" (which is quite possible).



This is how it gets replaced by the macro


int temp;
temp=temp;
temp=b;
b=temp;