将一个4字节的整数的二进制表示中的001替换为011,输出替换后的整数

#include<stdio.h>
#include<string.h>
#include<math.h>
/***将十进制转换成二进制,采用递归方法***/
char * DectoBin(int n)
{   
	   static char bin[32]="0000000000000000000000000000000";
       static i = 0;	   
	   	int temp ;
		temp= n%2;
		n = n/2;
		if(n==0)
		{
		  if(temp==0)
		  {
			  bin[31-i]='0';
			  
		  }
		      
		  else
		  {
			  bin[31-i]='1';
		       
		  }
			  i++;
		  return bin;
		}
		else
		{  
			if(temp==0)
			{
				bin[31-i]='0';
			
			}
			
			else
			{
				bin[31-i]='1';
			
			}
			  i++;
	       DectoBin(n);
		}
		return bin;
}
/***将001替换成011**/

char * replace001(char *s,char *p)
{
	char *temp=s;
	while(temp!=NULL)
	{
		temp=strstr(temp,"001");
		if(temp)
		{
         
		  strncpy(temp,"011",3);
	       temp++;
		}
		
		
	}

	return s;
}
/**将二进制转换成10进制**/
int BintoDec(char *bin)
{
    int i,j=0;
    char string[33]="0000000000000000000000000000000";
	int Dec=0,temp=bin;
    for(i=31;i>=0;i--)
	{
		string[j++]=*(bin+i);
	}
	 string[33]='\0' ;
	    
     printf("string=%s\n",string);
	 for(j=0;j<32;j++)
	 {
		 temp=string[j]-'0';
	     Dec+=temp*pow(2,j);
	 }
		   printf("string=%d\n",Dec);
	return Dec;
}

void main()
{
   char *temp2;
   char *temp=DectoBin(3);
   printf("The binary is %s\n",temp);
   temp2=replace001(temp,"001");
   printf("The binary is %s\n",temp2);
   printf("the int is %d\n",BintoDec(temp2));
   
}

猜你喜欢

转载自blog.csdn.net/fengliang191/article/details/38964493