题解 | #整数与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-29 17:30
找实习找着找着就要进入7月了,马上秋招也要开始了,找实习还有意义吗?
绝迹的星:有面就面, 没面上就当日薪4位数大佬免费培训, 面上了再考虑要不要实习
点赞 评论 收藏
分享
下个早班:秒挂就是不缺人
点赞 评论 收藏
分享
流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

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