您的位置:首页 > 其它

NYOJ630 Problem of IP

2014-03-01 23:51 134 查看
原题链接

十进制转换成二进制时要注意不足补0,二进制转十进制不需要考虑这种情况。

#include <stdio.h>
#include <string.h>
char str[35], buf[35];

void f1(){
int t, i;
char *p = strtok(str, ".");
buf[8] = '\0';
while(p != '\0'){
sscanf(p, "%d", &t);
i = 8;
while(t){
buf[--i] = t % 2 + '0';
t /= 2;
}
while(i) buf[--i] = '0';
printf(buf);
p = strtok(NULL, ".");
}
puts("");
}

void f2(char *s){
int t, i = 0;
while(s[0] != '\0'){
t = 0;
for(i = 0; i <= 7; ++i)
t = t * 2 + s[i] -'0';
printf("%d", t);
s += 8;
if(s[0] != '\0') putchar('.');
}
puts("");
}

int main(){
while(scanf("%s", str) == 1)
if(strchr(str, '.')) f1();
else f2(str);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: