Saturday, November 28, 2009

To determine whether machine is Little-Endian and Big-Endian?

Problem Write a program to find whether a machine is big endian or little endian. Solution What Little-Endian and Big-Endian? How can I determine whether a machine's byte order is big-endian or little endian? How can we convert from one to another? First of all, Do you know what Little-Endian and Big-Endian mean? Little Endian means that the lower order byte of the number is stored in memory at the lowest address, and the higher order byte is stored at the highest address. That is, the little end comes first. For example, a 4 byte, 32-bit...

Friday, November 27, 2009

Calculate pow function

Lets look at some solutions. Solution 1 - Using recursion int pow(int x, int y) { if(y == 1) return x ; return x * pow(x, y-1) ; } Divide and Conquer C program /* Function to calculate x raised to the power y */ int power(int x, unsigned int y) { if( y == 0) return 1; else if (y%2 == 0) return power(x, y/2)*power(x, y/2); else return x*power(x, y/2)*power(x, y/2); } /* Program to test function power */ int main() { int x = 2; unsigned int y = 3; printf("%d", power(x, y)); getchar(); ...

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. b=a^b: 'b' will compare to the difference between a and b: for the bit that 'b' and 'a' differ, it means a have 1 at...