Tuesday, November 5, 2013

Bit Fiddling !!

Bit fields are one of the most important aspects of embedded programming . Let us see few tricky and interesting cases in that field .. 1. Searching for the no of bits set in a given number -- Let us see with an example how we can check for the no of bits set in a number
#include<stdio.h>
#include<sys/time.h>
#include<string.h>
#include<time.h>

char *time_stamp()
{
  static char buf[100];
  char timestamp[100];
  time_t time;
  struct timeval detail_time;
  memset (buf, 0, 100);
  gettimeofday(&detail_time,NULL);
  time = detail_time.tv_sec;

  strftime(timestamp, 100, "%Y/%m/%d %H:%M:%S", localtime(&time));
  sprintf(buf, "%s:%ld:%ld ", timestamp,
          detail_time.tv_usec /1000, detail_time.tv_usec%1000);
 
  return buf;
}

int main()
{
int test ;
int temp,i=0;
char bits_count= 0;
printf("Enter any number \n");
scanf("%d",&test);
temp =test;

printf("Time stamp 1 is %s \n",time_stamp());
/* Method -1 */
do {
if(temp & 1)
  bits_count++;
temp = temp >>1;
}while((i++)<(sizeof(int)*8));

printf("No_of_bits_set are %d\n",bits_count);
printf("Time stamp 2 is %s \n",time_stamp());

bits_count= 0;
temp =test;
/* Method - 2*/
while(temp)
{ 
 if(temp & 1)
  bits_count++;
 temp =temp >>1;
};
printf("No_of_bits_set are %d\n",bits_count);
printf("Time stamp 3 is %s \n",time_stamp());

/*Method -3 */
bits_count= 0;
temp =test;

while(temp)
{ 
 if(!((char)temp & 0xff))
 temp = temp >> 8;
 else if(temp & 1)
  bits_count++;
 temp =temp >>1;
};


printf("No_of_bits_set are %d\n",bits_count);
printf("Time stamp 4  is %s \n",time_stamp());

return 0 ;

}

Enter any number 32 <<< one of the worst case scenarios ! Time stamp 1 is 2012/11/02 23:32:47:413:450 No_of_bits_set are 1 Time stamp 2 is 2012/11/02 23:32:47:413:774 <<<< approx 300 Micro seconds No_of_bits_set are 1 Time stamp 3 is 2012/11/02 23:32:47:413:809 <<<< approx 35 Micro seconds No_of_bits_set are 1 Time stamp 4 is 2012/11/02 23:32:47:413:832 <<< approx 23 Micros !!!! :-) << similarly can be calculated for other number as well .... Enter any number 65535 Time stamp 1 is 2012/11/02 23:33:10:851:616 No_of_bits_set are 16 Time stamp 2 is 2012/11/02 23:33:10:851:973 No_of_bits_set are 16 Time stamp 3 is 2012/11/02 23:33:10:852:8 No_of_bits_set are 16 Time stamp 4 is 2012/11/02 23:33:10:852:31

Popular Posts