我在这里有一些问题,我想转换这个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语言工作。
谢谢
答案 0 :(得分:2)
看起来您想将IPv6地址转换为四个整数。如果它们在您的环境中可用,我建议您利用现有的库函数来完成此任务。具体来说,inet_ntop
可以将您的字符串转换为struct in6_addr
,这应该更容易处理。
答案 1 :(得分: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;
}