如果我在char地址[4]中存储了4字节地址,则内容为:
address[0] = '\x80';
address[1] = '\xAB';
address[2] = '\x0A';
address[3] = '\x1C';
// all together: 80 AB 0A 1C
我想将它转换为一个看起来像“128.171.10.28”的字符数组,因为十六进制中的80是128,十六进制中的AB是171,依此类推。
我该怎么做?
答案 0 :(得分:9)
char saddr[16];
sprintf(saddr, "%d.%d.%d.%d", (unsigned char)address[0], (unsigned char)address[1], (unsigned char)address[2], (unsigned char)address[3]);
或
char saddr[16];
unsigned char *addr = (unsigned char*)address;
sprintf(saddr, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]);
或者,正如dreamlax指出的那样:
char saddr[16];
sprintf(saddr, "%hhu.%hhu.%hhu.%hhu", address[0], address[1], address[2], address[3]);
答案 1 :(得分:5)
IP地址只是以a为单位打印的单个八位字节,以a分隔。
printf("%d.%d.%d.%d",address[0],address[1],address[2],address[3]);
您可能应该将char address[4]
设为unsigned char address[4]
答案 2 :(得分:-1)
使用%u会更好。