Thursday, August 7, 2014

C Programming : Number of ones in a binary for an integer number without a loop


  #include"stdio.h"
  //#define DEBUG

/* Note :-
 * char array notation :- ((unsigned char *)&number)[p]
 * Byte - 8 bit.
 * e58e9bc0  - hex, - 4byte
 * 32bit - 8 hex numbers
 * each hex number is 32/8 = 4 bits
 * "f" in hex is 1111
 */

  int number_of_ones(int j);

  #define byte_extract(number,p)   ((unsigned char *)&number)[p]  
 
  int array[16] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
 
 int main()
 {
     int j = 0;

      printf("/******** THIS PROGRAM GIVES NUMBER OF ONES IN A NUMBER,");
      printf("LOOPS ARE NOT USED FOR CODE EFFICIENCY ****************/\n");

      printf("Enter a number(Decimal Format) : ");

      scanf("%d",&j);

#ifdef DEBUG
      printf("%d,%d,%d,%d,%d,%d,%d,%d\n",array[(byte_extract(j,0) & 0xf)],
      array[((byte_extract(j,0) & 0xf0) >> 4)] ,
      array[(byte_extract(j,1) & 0xf)] , array[((byte_extract(j,1) & 0xf0) >> 4)] ,
      array[(byte_extract(j,2) & 0xf)]  , array[((byte_extract(j,2) & 0xf0) >> 4)] ,
      array[(byte_extract(j,3) & 0xf)]  , array[((byte_extract(j,3) & 0xf0) >> 4)] );
#endif

     printf("Number of ones in the number 0x%x(Hex) are %d\n",j ,number_of_ones(j));
}


int number_of_ones(int j)
{
     return  (array[(byte_extract(j,0) & 0xf)] + array[((byte_extract(j,0) & 0xf0) >> 4)] +
              array[(byte_extract(j,1) & 0xf)] + array[((byte_extract(j,1) & 0xf0) >> 4)] +
              array[(byte_extract(j,2) & 0xf)] + array[((byte_extract(j,2) & 0xf0) >> 4)] +
              array[(byte_extract(j,3) & 0xf)] + array[((byte_extract(j,3) & 0xf0) >> 4)] );
}


No comments:

Post a Comment