将4字节的ip地址转换为标准的点分十进制表示法 [英] Converting a 4 byte ip address to standard dotted decimal notation

查看:116
本文介绍了将4字节的ip地址转换为标准的点分十进制表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在char地址[4]中存储了一个4字节的地址,内容为:

If I have a 4 byte address stored in char address[4] and the contents are:

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,依此类推.

I want to convert it to a character array that looks like "128.171.10.28", since 80 in hex is 128, AB in hex is 171 and so on.

我该怎么做?

推荐答案

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所指出的:

or, as pointed out by dreamlax:

char saddr[16];
sprintf(saddr, "%hhu.%hhu.%hhu.%hhu", address[0], address[1], address[2], address[3]);

这篇关于将4字节的ip地址转换为标准的点分十进制表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆