This program is to convert a base 4 number to a base 2 number and it should be done in place
#include<stdio.h>
#include<string.h>
void shiftr(char num[],int i)
{
memmove(num+i,num+i+1,strlen(num)-i);
}
char* convert4to2(char num[])
{
int i=0,len;
char ch;
while(num[i]!='\0')
{
ch=num[i];
shiftr(num,i);
switch(ch)
{
case '0':num[i++]='0';
num[i++]='0';
break;
case '1':num[i++]='0';
num[i++]='1';
break;
case '2':num[i++]='1';
num[i++]='0';
break;
case '3':num[i++]='1';
num[i++]='1';
break;
default:printf("Error");
}
}
num[i]='\0';
return(num);
}
void main()
{
char num[20];
printf("Enter the Base 4 Number:");
scanf("%s",&num);
printf("The Binary Equivalent is:%s\n",convert4to2(num));
}
The output for an input of 121(base 4 number) should be 011001 but its displaying only 01. And for larger numbers like 12101 it displays 0100 taking the first and the last but one numeral. What could be the problem?
You're actively destroying your input. E.g., for the first iteration, you shift your number by one place and after that you overwrite the data at place 0 and place 1 (which contains the next 2 digits in 4-base) with your binary output for the 1st digit.