Saturday, August 7, 2010

Code to find if a given integer number is power of 2

this can be done in 2 ways


1)
if(!(x& (x - 1)) && x)
 {
     printf("GIVEN NUMBER IS POWER OF 2");
}
EXPLANATION:


Let n be the position of the leftmost 1 bit if x. If x is a power of two, its lone 1 bit is in position n. This means x – 1 has a 0 in position n. To see why, recall how binary subtraction works. When subtracting 1 from x, the borrow propagates all the way to position n; bit n becomes 0 and all lower bits become 1. Now, since x has no 1 bits in common with x – 1, x & (x – 1) is 0, and !(x & (x – 1)) is true.

2)
if(((~x+1)&x)==i)
{
     printf("GIVEN NUMBER IS POWER OF 2");
}
EXPLANATION:
The two’s complement of x is computed with ~x + 1, which inverts the bits of x and adds 1 (~x + 1 is equivalent to -x, but negation is technically illegal for an unsigned integer

Let n be the position of the leftmost 1 bit if x. If x is a power of two, its lone 1 bit is in position n. This means ~x has a 0 in position n and 1s everywhere else. When 1 is added to ~x, all positions below n become 0 and the 0 at position n becomes 1. In other words, the carry propagates all the way to position n. So what happens is this: negating x inverts all its bits, but adding 1 inverts them back, from position n on down. So, (x & (~x + 1)) == x is true.

C Code to convert from decimal to any base Like binary, hex, oct

/* Here we use a single function which can be used to convert a decimal number to any base */

#include
void  DecimalToAnybase(int n, int base);
/*n is decimal no & base indicates to which form the decimal no has to get changed*/
#define HEXADECIMAL  16
#define BINARY                2
#define OCTAL                  8
int main()
{
       DecimalToAnybase(10, BINARY);
      
DecimalToAnybase(255, OCTAL);
        getch();
}
  void 
DecimalToAnybase(int n, int base)
       {
           int i, m, digits[1000], flag;
           i=0;
           printf("\n\n[%d] converted to base [%d] : ", n, base);
           while(n)
           {
                m=n%base;
                digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];
                n=n/base;
                i++;
            }
         / /Eliminate any leading zeroes
           for(i--;i>=0;i--)
           {
              if(!flag && digits[i]!='0')flag=1;
              if(flag)printf("%c",digits[i]);
            }
          }

Various ways to swap two variables without using a temporary variable

The normal way of doing a simple swap is as follows.
int a,b,t;
t = a;
a = b;
b = t;
But this can be done in different methods with out using an extra or temporary variable but each  method has its own flaws.

Method1 (The XOR trick)

a ^= b ^= a ^= b;
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. . Also, think of a scenario
where you have written your code like this
swap(int *a, int *b)
{
*a ^= *b ^= *a ^= *b;
}
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;
}
}

Method2(using + and - )


This method is also quite popular
a=a+b;
b=a-b;
a=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.
Method3(using macro)
One can also swap two variables using a macro. However, it would be required to pass the type of the variable to the macro. Also, there is
an interesting problem using macros. Suppose you have a swap macro which looks something like this
#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;
Which means it sets the value of "b" to both the variables!. It never swapped them! Scary, isn't it?
Conclusion:
 Use a temporary variable. Its not only fool proof, but also easier to understand and maintain as trying to do something tricky will have some or the other loopholes which are very difficult to identify at the first glance.

Wednesday, August 4, 2010

FILE COPY CODE (CP cmd in Unix) basic version of CP command

/*    Basic FILE COPY FUNCTION IN UNIX SIMILAR TO CP COMMAND  */


#include
#define MAX_LINE_LEN 1000      /* maximum line length supported. */
void main(int argc, char* argv[])
{
      char* filePathFrm;
      char* filePathTo;
      FILE* fFrm;
      FILE* fTo;
      char buf[MAX_LINE_LEN+1];
      filePathFrm = "";
      filePathTo = "";
      fFrm = fopen(filePathFrm, "r");
      if (!fFrom) 

      {
        // Print log or some exception handling
            perror("source Fileopen failed:");
            exit(1);
      }
      f_to = fopen(file_path_to, "w+");
       if (!f_to)
       {
         // Print log or some exception handling
          perror("destination fileopen failed:")
          exit(1);
       }
         /* Copy source to target, line by line. */
     while (fgets(buf, MAX_LINE_LEN+1, f_from))
     {
         if (fputs(buf, f_to) == EOF)
          {
                    exit(1);
           }
     }
     if (!feof(f_from))
     {
       
         exit(1);
     }
     if (fclose(f_from) == EOF)
     {
        exit(1);
      }
     if (fclose(f_to) == EOF)
     {
        exit(1);
     }
     return(0);
}


NOTE:
  •  fopen() function shall open the file whose pathname is the string pointed to by filename, and associates a stream with it.returnvalue:Pointer to the opened files object.on failure it returns NULL
  •  fclose() function causes the stream pointed to by stream to be flushed and the associated file to be closed . returnvalue:  0on succes. Otherwise, it returns EOF.
  • feof() function tests the end-of-file indicator for the stream pointed to by stream. returnvalue: non-zero if and only if the end-of-file indicator is set for stream
  • perror():The perror() function shall map the error number accessed through the symbol errno to a language-dependent error message.returnvalue:no return value
        

Tuesday, August 3, 2010

C code for Comparision of 2 Given Strings

/*        strcmp() function defination in c       */
int myStrCmp(const char *s1, const char *s2)
{
    while (*s1==*s2)
    {
       if(*s1=='\0')
          return(0);
         s1++;
         s2++;
    }
     return(*s1-*s2);/*an integer greater than, equal to, or less than 0, if the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2, respectively.*/
}
/* const keyword : is used so that the data pointed by s1 and s2 remains unchanged and if any statement tries to modifie it ,then the compiler will post an error so in order to safe guard some information which we expect to be unchaged we declare it with the key word const */

C Code To find the Factorial of a Number(Recursive function Call)

/***********Factorial of a Number ( recursive C program) ************/
int fact(int n)
{
    int fact;
    if(n==1 || n==0)
       return(1);
    else
        fact = n * fact(n-1);
   return(fact);
}
/* Implementing code in recursive manner is avoided in most cases as it reduces coding complexity and increases the overhead as lot of stacks get created as the function gets called again and again recursively */

C CODE FOR strcat() function

/*******MY STRCAT FUNCTION *************/
char *myStrcat(char *s, const char *t)
{
    char *p = s;
    if (s == NULL || t == NULL) 
        return s;
    while (*s)
       s++;
    while (*s++ = *t++);
   return p;
}

counter