Embedded C to find the number of one’s in a given 32bit number and optimize the code
In this article let’s learn how to optimize a program.The program which is used for optimization is to find number of ones in a given 32bit number. First let’s write a simple code and then let’s see how to optimize it.
Algorithm:
1)Start
2)Assign the 32bit number
3)Divide the number by 2 and store it’s remainder
4)Compare the remainder to 1 and update the counter if it is true
5)divide the number by 2 and update the number by it’s quotient
6)Repeat the step 3,4 and 5 by 32 times as it is 32 bit number
7)Stop
Code goes here:
#include void main() { int num=10,i,rem,count=0; for(i=0;i<32;i++) { rem=num%2; //Store the remainder num=num/2;//Divide the number by 2 if(rem==1) count++;//increment the counter } }
Alternate method:
I know this program will give you correct results but what if the number is too small don’t you think the processor will unnecessarily goes into 32 loops.So here is another logic to reduce number of loops.
Algorithm:
1)Start
2)Logical AND the number with 1 and check if the number is 1 so that it checks the lowest bit of number
3)Right shift the number by one unit
4)Repeat the step 2 and 3 until the number is equal to 0
5)Stop
Code goes here:
#include<stdio.h> void main() { int num=10,count=0; while(num)//Get into the loop until the number is zero { if(num&01)//Logical And the number with one count++; num=num>>1;//Right shift the number one unit } }
Alternate method:
You know guys you can further reduce the program by looping the binary number according to the number of ones in the program.
Algorithm:
1)Start
2)Logical AND the number by number-1
3)If the number is greater than zero increment the counter
3)Repeat until the number is zero
4)Stop
#include<stdio.h> void main() { int num=10,count=0; for(;num;num&=num-1) //In place of update And the number by num-1 count++; }
Conclusion:
We can see in the above program as we reduce the number of loops and decrease the number of lines of the program the execution time of the processor increases and the memory decreases.