#include<stdio.h>

#define SIGNOF(i) ((unsigned)(i) >> (sizeof (int) * 8 - 1))

#define CHECKMSB(type,a,b) ((a-b) & ((1 << (sizeof(type) * 8) - 1)))

int max(int a, int b)

{

int p[2] = {a,b};

return p[SIGNOF(a - b)];

}

int max_bymsb(int a, int b)

{

return CHECKMSB(int,a,b) ? b:a;

}

void main()

{

int a = 55,b = 30;

int x=max(a,b);

printf("Maximum number : %d\n",x);

printf("a-b : %x\n",(a-b));

printf("1 shift 31 times : %x\n",1 << 31);

printf("sizeof int : %d\n",(((sizeof(int) * 8)- 1)));

printf("Flag : %x\n",CHECKMSB(int,a,b));

printf("Max : %d\n",max_bymsb(a,b));

}

Maximum number: 55

a-b : 19

1 shift 31 times : 80000000

sizeof int : 31

Flag : 0

Max : 55

Here Program you can see the two different Macro is used. Both is used to check the sign or MSB of the number.

But Why we need to check the MSB or Sign?

Logic is very simple. We can judge the bigger number based on sign value.

1)

If we subtract the bigger value from small value then we will get the negative number means sign is 1.

2)

But If subtract smaller value from bigger value then we will get positive number means sign is 0.

We know what we are subtracting and from what. So based on that we can get the smaller and bigger value.

If you feel there can be a scope of improvement in this then please suggest.

#define SIGNOF(i) ((unsigned)(i) >> (sizeof (int) * 8 - 1))

#define CHECKMSB(type,a,b) ((a-b) & ((1 << (sizeof(type) * 8) - 1)))

int max(int a, int b)

{

int p[2] = {a,b};

return p[SIGNOF(a - b)];

}

int max_bymsb(int a, int b)

{

return CHECKMSB(int,a,b) ? b:a;

}

void main()

{

int a = 55,b = 30;

int x=max(a,b);

printf("Maximum number : %d\n",x);

printf("a-b : %x\n",(a-b));

printf("1 shift 31 times : %x\n",1 << 31);

printf("sizeof int : %d\n",(((sizeof(int) * 8)- 1)));

printf("Flag : %x\n",CHECKMSB(int,a,b));

printf("Max : %d\n",max_bymsb(a,b));

}

**Output:**Maximum number: 55

a-b : 19

1 shift 31 times : 80000000

sizeof int : 31

Flag : 0

Max : 55

Here Program you can see the two different Macro is used. Both is used to check the sign or MSB of the number.

But Why we need to check the MSB or Sign?

Logic is very simple. We can judge the bigger number based on sign value.

1)

If we subtract the bigger value from small value then we will get the negative number means sign is 1.

2)

But If subtract smaller value from bigger value then we will get positive number means sign is 0.

We know what we are subtracting and from what. So based on that we can get the smaller and bigger value.

If you feel there can be a scope of improvement in this then please suggest.

## 0 comments :

## Post a Comment