Wednesday 28 June 2017

Embedded C Programs

Find the size of structure without using sizeof()
struct MyStruct {
   int i; 
   int j;
 }; 

int main() { 
   struct MyStruct *p=0; 
   int size = ((char*)(p+1))-((char*)p); 
   printf("\nSIZE : [%d]\nSIZE : [%d]\n", size); 
   return 0; 
}  

swap the two nibbles in a byte 


unsigned char swap_nibbles(unsigned char c)
{
 unsigned char temp1, temp2;
 temp1 = c & 0x0F;
 temp2 = c & 0xF0;
 temp1=temp1 << 4;
 temp2=temp2 >> 4;
 return(temp2|temp1); //adding the bits
} 

multiply a number by 7
 
(num<<3 -="" 7="" as="" br="" is="" nbsp="" num="" same="" this="">
 
find out if a machine is 32 bit or 64 bit
compilers keep the size of integer the same as the size of the register on a perticular architecture. Thus, to know whether the machine is 32 bit or 64 bit, just see the size of integer on it.

sum the digits of a given number  
 while(num>0)
{
    sum+=num%10

    num/=10);
}

the stack grows up or down

void stack(int *local1)
{
 int local2;
 printf("\nAddress of first local : [%u]", local1);
 printf("\nAddress of second local : [%u]", &local2);
 if(local1 < &local2)
 {
 printf("\nStack is growing downwards.\n");
 }
 else
 {
 printf("\nStack is growing upwards.\n");
 }
 printf("\n\n");
}
 count bits set in an integer
#include
int main()
{
 int num=10;
 int ctr=0;

 while(num)
 {
   ctr++;
   num = num & (num - 1); // This clears the least significant bit set.
 }
 
 printf("\n Number of bits set in [%d] = [%d]\n", num, ctr);
 return(0);
} 
 reverse the bits in an interger
/* Function to reverse bits of num */
unsigned int reverseBits(unsigned int num)
{
    unsigned int  NO_OF_BITS = sizeof(num) * 8;
    unsigned int reverse_num = 0, i, temp;
 
    for (i = 0; i < NO_OF_BITS; i++)
    {
        temp = (num & (1 >> i));
        if(temp)
            reverse_num |= (1 << ((NO_OF_BITS - 1) - i));
    }
  
    return reverse_num;
}
 


No comments:

Post a Comment