## Saturday, November 28, 2009

### 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 integer
```    Byte3 Byte2 Byte1 Byte0
```

will be arranged in memory as follows:
```    Base_Address+0   Byte0
```

Intel processors use "Little Endian" byte order.

Big Endian means that the higher order byte of the number is stored in memory at the lowest address, and the lower order byte at the highest address. The big end comes first.
```  Base_Address+0   Byte3
```

Motorola, Solaris processors use "Big Endian" byte order.

In "Little Endian" form, code which picks up a 1, 2, 4, or longer byte number proceed in the same way for all formats. They first pick up the lowest order byte at offset 0 and proceed from there. Also, because of the 1:1 relationship between address offset and byte number (offset 0 is byte 0), multiple precision mathematical routines are easy to code. In "Big Endian" form, since the high-order byte comes first, the code can test whether the number is positive or negative by looking at the byte at offset zero. Its not required to know how long the number is, nor does the code have to skip over any bytes to find the byte containing the sign information. The numbers are also stored in the order in which they are printed out, so binary to decimal routines are particularly efficient.

Here is some code to determine what is the type of your machine
```int num = 1;
if(*(char *)&num == 1)
{
printf("\nLittle-Endian\n");
}
else
{
printf("Big-Endian\n");
}

```

If it is little endian, the num in the memory will be something like:
```       higher memory
----->
+----+----+----+----+
|0x01|0x00|0x00|0x00|
+----+----+----+----+
A
|
&num

```

so (char*)(*num) == 1, will be true, as it will take first byte. If it is big endian, it will be:
```    +----+----+----+----+
|0x00|0x00|0x00|0x01|
+----+----+----+----+
A
|
&num

```
so this one will be '0'.
And here is some code to convert from one Endian to another.

```int myreversefunc(int num)
{
int byte0, byte1, byte2, byte3;

byte0 = (num & x000000FF) >>  0 ;
byte1 = (num & x0000FF00) >>  8 ;
byte2 = (num & x00FF0000) >> 16 ;
byte3 = (num & xFF000000) >> 24 ;

return((byte0 << 24) | (byte1 << 16) |

(byte2 << 8) | (byte3 << 0));
}
```

Lets go to other languages - Java and .net

In java:
```import java.nio.ByteOrder;

if (ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN)) {
System.out.println("Big-endian");
} else {
System.out.println("Little-endian");
}
```

In .Net
```BitConverter.IsLittleEndian
```

References
http://stackoverflow.com/questions/12791864/c-program-to-check-little-vs-big-endian
http://stackoverflow.com/questions/9431526/find-endianness-of-system-in-java
http://stackoverflow.com/questions/4181951/how-to-check-whether-a-system-is-big-endian-or-little-endian

## 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();
return 0;
}
```

Time Complexity: O(n)
Space Complexity: O(1)
Above function can be optimized to O(logn) by calculating power(x, y/2) only once and storing it.
```/* Function to calculate x raised to the power y in O(logn)*/
int power(int x, unsigned int y)
{
int temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
else
return x*temp*temp;
}

```

Time Complexity of optimized solution: O(logn)
Let us extend the pow function to work for negative y and float x.
```* Extended version of power function that can work
for float x and negative y*/
#include<stdio.h>

float power(float x, int y)
{
float temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
else
{
if(y > 0)
return x*temp*temp;
else
return (temp*temp)/x;
}
}

/* Program to test function power */
int main()
{
float x = 2;
int y = -3;
printf("%f", power(x, y));
getchar();
return 0;
}
```

Source -http://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/

Thanks.

### 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;
```

### 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 this position and the result of a^b will assign that bit to 1; for the bit that 'b' and 'a' agree, it means a have 0 at this position and the result of a^b will assign that bit to 0.
• a=a^b:  same logic
Although the code above works fine for most of the cases, it tries to modify variable 'a' two times between sequence points, so the behavior is undefined. What this means is it wont work in all the cases. This will also not work for floating-point values. Also, think of a scenario where you have written your code like this

Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already equal to each other.

```swap(int *a, int *b)
{
if(*a!=*b)
{
*a ^= *b ^= *a ^= *b;
}
}
```

Method 2 - Simple addition and subtraction

This method is also quite popular
``` a=a+b;
b=a-b;
a=a-b;
```

OR
```a =((a = a + b) - (b = a - b));
```
But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this might end up giving you wrong results.