Swap odd and even bits in an integer
Problem
Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc).
Input : An integer x
Output : An integer y, which odd and even bit swapped (with 0th bit being least significant bit)
Example
Input 1: 10 = 1010 Output 1: 5 = 0101 (0th bit and 1st bit have been swapped,also 2nd and 3rd bit have been swapped) Input 2: 14 = 1110 Output 2: 13 = 1101 Solution
[Read More]
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;
}
Swapping 2 variables using macro
Problem
How to swap 2 variables using macro?
Solution
#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;
Swap two number in place without temporary variables.
Problem Write a function to swap two number in place without temporary variables.
Solution Method1 - The XOR or Exclusive trick
In C this should work:
a ^= b ^= a ^= b; to simplify :
a=a^b; b=a^b; a=a^b; OR
a^=b; b^=a; a^=b; Following are operations in XOR
0^0=0 0^1=1 1^0=1 1^1=0 Hence, we have:
a=a^b: ‘a’ will save all the bits that a differs from b: if the bit that ‘a’ and ‘b’ differ, it gets 1, otherwise 0.
[Read More]