I have written a program that will convert a number into string. The core logic is using % 10. However, I am looking for some other way. The other way should be using bitwise operator. The first question comes to my mind is how to split the digits using bitwise operation. I am unable to think on those lines. Here is my usual program.
#include "stdio.h"
void itoaperChar(int n, char *s)
{
s[0] = '0' + n;
s[1] = '\0';
}
typedef struct my_string
{
char val;
struct my_string *next;
}my_string;
void convertitoString(int nu, char *des)
{
char tempChar[2];
my_string *Head = NULL;
my_string *tempNode = NULL;
while( nu != 0)
{
/** when we apply the logic of traversing from last, the data is accessed as LIFO **/
/** we are again applying LIFO to make it FIFO **/
int temp = nu%10;
itoaperChar(temp,&tempChar);
if(Head == NULL )
{
Head =(my_string*)malloc(sizeof(my_string));
/** Remember, strcpy looks for \0 in the source string. Always, ensure that the string is null terminated. Even if the string is just 1 byte.**/
strcpy(&(Head->val),tempChar);
Head->next = NULL;
}
else
{
tempNode = (my_string*)malloc(sizeof(my_string));
strcpy(&(tempNode->val),tempChar);
tempNode->next = Head;
Head = tempNode;
}
nu = (nu - temp)/10;
}
int lcindex = 0;
while(Head!=NULL)
{
strcpy(&(des[lcindex]),&(Head->val));
lcindex++;
tempNode = Head;
Head=Head->next;
free(tempNode);
tempNode = NULL;
}
des[lcindex] = '\0';
}
void main()
{
char t[10];
convertitoString(1024,t);
printf("The value of t is %s ", t);
}