Wednesday 28 June 2017

Common C-Programs

/*Recursive Example*/
int pow(int x, int y) {
  if(y == 1) return x ;
   return x * pow(x, y-1) ;
}
================
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.
For example, 
  a 4 byte, 32-bit integer 
    Byte3 Byte2 Byte1 Byte0 
  will be arranged in memory as follows: 
    Base_Address+0     Byte0
    Base_Address+1    Byte1 
     Base_Address+2    Byte2 
     Base_Address+3   Byte3  



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
 Base_Address+1  Byte2 
 Base_Address+2   Byte1 
 Base_Address+3  Byte0 
Motorola, Solaris processors use "Big Endian" byte order.


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)); 


 ==========================
Check if an integer is a power of 2 or not
 
if(!(num & (num - 1)) && num) {
  // Power of 2! 
}

===================================
maximum of three integers using the ternary operator
max = ((a>b)?((a>c)?a:c):((b>c)?b:c));  

find the max of 4 numbers... 
#define   max2(x,y)   ((x)>(y)?(x):(y))
#define   max4(a,b,c,d)   max2(max2((a),(b)),max2((c),(d))) 
======================================
dynamically allocate one, two dimensional arrays 
One dimensional array 
int *myarray = malloc(no_of_elements * sizeof(int)); 
//Access elements as my array[i] 

Two dimensional array 
 int **myarray = (int **)malloc(no_of_rows * sizeof(int *)); 
for(i = 0; i < no_of_rows; i++) { 
  myarray[i] = malloc(no_of_columns * sizeof(int)); 
} // Access elements as myarray[i][j] 
 

No comments:

Post a Comment