-9

我有一些麻烦,我想转换这个 char 数组

char IP[]="2001:2AB1:30A1:2000:1000:ABC1"

to 4 int key1,key2,key3,key4 with 
key1=2001
key2=2AB1
key3=30A1
key4=2000:1000:ABC1

我用 C 语言工作。

谢谢

4

2 回答 2

2

看起来您想将 IPv6 地址转换为四个整数。如果它们在您的环境中可用,我建议您利用现有的库函数来完成此任务。具体来说,inet_ntop可以将您的字符串转换为struct in6_addr应该更容易处理的字符串。

于 2013-06-15T20:26:59.967 回答
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

char *strdelch(char *str, char ch){
    char *from, *to;
    if(NULL==str)return str;

    from=to=str;
    while(*from){
        if(*from != ch)
            *to++ = *from;
        ++from;
    }
    *to = '\0';
    return str;
}

int main(void){
    char IP[]="2001:2AB1:30A1:2000:1000:ABC1";
    int key1,key2,key3;
    int64_t key4;
    char *p = IP;

    key1 = strtol(p, &p, 16);
    key2 = strtol(++p, &p, 16);
    key3 = strtol(++p, &p, 16);
    key4 = strtoll(strdelch(++p, ':'), NULL, 16);
    printf("%04X\n", key1);
    printf("%04X\n", key2);
    printf("%04X\n", key3);
    printf("%012I64X\n", key4);
    return 0;
}
于 2013-06-15T21:02:25.110 回答