Saturday, October 27, 2007

Simple yet useful C programs

All functions written below are compiled on gcc.
1) Function to count number of ones and zeros in a given integer
Input Params :
a)num: The integer for which count needs to be dome
b)one_count : pass the address of variable in which 1's count is expected
c)one_count : pass the address of variable in which 0's count is expected

void count_OneAndZero(int num, int *one_count, int *zero_count)
{
while(num != 0){
if(num&1)
*one_count +=1;
num >>=1;
}
*zero_count = sizeof(int)*8 - *one_count;
return;
}


2) Function to convert decimal to binary
Input Params :
a)decimal: The integer to be converted into binary
b)binary : The fixed size array in which binary string is expected.
void dec2bin(long decimal, char *binary)
{
int i = 0, j = 0;
int neg_flag = 0;
int remain;
char temp[80];

/* what if i/p is -ve */
if (decimal < 0)
{
decimal = -decimal;
neg_flag = 1;
}

if (neg_flag)
temp[i++] = '-'; // add - sign
else
temp[i++] = ' '; // space
while (i >= 0)
binary[j++] = temp[--i];
binary[j-1] = '\0'; // end with NULL
return;
}

No comments: