十进制转换成二进制时要注意不足补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; }