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

整数与IP地址间的转换

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

void rollback(char* str) {
    int len = strlen(str);
    for (int i = 0; i < len / 2; i++) {
        char tmp;
        tmp = str[i];
        str[i] = str[len - i - 1];
        str[len - 1 - i] = tmp;
    }
}

int main() {

    char str[20] = {'\0'};
    int dec_ip;
    scanf("%s %d", str, &dec_ip);
    str[strlen(str)] = '.';

    int duan_ip[5] = {0};
    int count = 0;
    char* p = strtok(str, ".");
    while (p != NULL) {
        duan_ip[count++] = atoi(p);
        p = strtok(NULL, ".");
    }

    unsigned int dec = (duan_ip[0] << 24) + (duan_ip[1] << 16) +
                        (duan_ip[2] << 8) + (duan_ip[3]);

    printf("%u\n", dec);

    for (int i = 0; i < 4; i++) {
        duan_ip[i] = (dec_ip >> ((3 - i) * 8)) & 0xff ;
    }

    printf("%d.%d.%d.%d\n", duan_ip[0], duan_ip[1], duan_ip[2], duan_ip[3]);

    return 0;
}

全部评论
玩单片机的把按位运算这种手段忘了,惭愧 - - ..
点赞 回复 分享
发布于 2023-03-08 20:32 陕西

相关推荐

10-28 14:42
门头沟学院 Java
watermelon1124:因为嵌入式炸了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务