Original link:
http://c.biancheng.net/c/
Problem description:
Suppose you want to write a program, a 32-bit binary IP address (32 characters long and 1 0) is converted to decimal point format and output. Point IP address by decimal notation 32 from low to high (right to left) a packet eight, four times in total, any 8-bit binary number corresponding to the decimal part of the IP address is valid.
C language code for:
/*
问题描述:
假设正在读取表示IP地址的字节流,任务是将32个字符长的1和0(位)序列转换为点分十进制格式,IP地址的点分十进制
格式是通过将32位字节流一次分组8位,并将二进制表示转换为十进制表示形式
*/
#include <stdio.h>
#include <string.h>
#define base 2
int main(void)
{
int n;
printf("请输入需要将32位二进制IP地址转化为点分十进制格式的数量:");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
char s[40];
int sum=0,flag=0;//flag为控制分隔符"."的输出
scanf("%s",s);
for(int j=0;j<strlen(s);j++)
{
sum=sum*base+s[j]-'0';//此处是重点,每8位二进制数转换为十进制数
if(j%8==7)//当j=7,15,23,31时开始输出
{
if(flag)
{
printf(".");//输出第一个八位二进制对应的十进制数时,不输出"."
}
printf("%d",sum);
sum=0;//sum置零,运算第二个八位二进制对应的十进制数
flag=1;//从第二个开始输出"."
}
}
printf("\n");
}
return 0;
}
Output: