#include<stdio.h>
#include<stdlib.h>
unsigned int *bin(int);
int main(void)
{
unsigned int n=0,*i=NULL;
printf("Enter no:");
scanf("%d",&n);
i=bin(n);
printf("Binary no: %d\n",*i);
return 0;
}
unsigned int *bin(int n)
{
unsigned int i=0,j=0;
static unsigned int *result=NULL;
result=(unsigned int*)malloc(1*sizeof(unsigned int));
printf("Result=%p\n",result);
j=(unsigned int)result;
for(i=(1<<31);i>0;i=(i>>1))
{
if(n & i)
{
*result=1;
result++;
}
else
{
*result=0;
result++;
}
}
result=(unsigned int*)j;
printf("Result=%p\n",result);
return result;
}
Output :
Enter no:6
Address of Result=0x2576010
Address of Result=0x2576010
Binary no: 0
The purpose of this program is to convert decimal number to binary number.The main function is calling the bin() function to convert decimal to binary.
Logic of Code :- Let us take unsigned integer (32 bit), which consist of 0-31 bits. To print binary representation of unsigned integer, start from 31th bit, check whether 31th bit is ON or OFF, if it is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print “1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation of number.
I am confused how much space should be malloced to store 32bits of integer.And how to free memory allocated to result.Please help me out with this code.