题解 | #整数与IP地址间的转换#

整数与IP地址间的转换

http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea

ip转整数,可以自己写个函数根据“.”分割,也可以直接用scanf函数。
然后用c语言的移位运算就很简单了。
#include "stdio.h"
#include "string.h"

unsigned int ip_to_uint(char* in_put) {
    char* p = in_put;
    int len = strlen(p);
    char tmp_str[32] = {0};

    if (len < 7) {
        return 0;
    }
    int a, b, c, d = 0;
    a = atoi(p);

    p = strchr(p, '.');
    if (p) {
        p++;
    } else {
        return 0;
    }
    b = atoi(p);

    p = strchr(p, '.');
    if (p) {
        p++;
    } else {
        return 0;
    }
    c = atoi(p);

    p = strchr(p, '.');
    if (p) {
        p++;
    } else {
        return 0;
    }
    d = atoi(p);

    snprintf(tmp_str, sizeof(tmp_str), "%d.%d.%d.%d", a, b, c, d);
    if (strcmp(in_put, tmp_str) != 0) {
        return 0;
    }
    return (a << 24 | b << 16 | c << 8 | d);
}


int main(void) {
    int i;
    int num = 0;
    char ip[16] = {0};
    char ip_int_str[16] = {0};
    int a, b, c, d;
//    scanf("%s", ip);
    scanf("%d.%d.%d.%d", &a, &b, &c, &d);
    scanf("%s", ip_int_str);
//    printf("%u\n", ip_to_uint(ip));

    printf("%u\n", a << 24 | b << 16 | c << 8 | d);
    unsigned int ip_int = strtol(ip_int_str, NULL, 10);
    printf("%d.%d.%d.%d", ip_int >> 24 & 0xff, ip_int >> 16 & 0xff,
           ip_int >> 8 & 0xff, ip_int & 0xff);
    return 0;
}



全部评论

相关推荐

点赞 评论 收藏
分享
06-08 22:25
门头沟学院 Java
从零开始的转码生活:这hr不会打开手机不分青红皂白给所有人群发这句话,过一会再给所有人再发一遍,这肯定会有重复的,不管,再过一会再发一遍
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务