我想将一个Uint32 IP地址转换为串联的字符串。
在此过程中,我得到了uint8数据,但我需要将其更改为const char*以便能够将其连接到IP的其他部分,以便在一个变量中打印完整的IP。
我该如何将uint8更改为const char*?或者是否有更好的转换方法?
uint32 ipAddress = GetHostIp();
if (ipAddress)
{
const int NBYTES = 4;
uint8 octet[NBYTES];
int x;
char *ipAddressFinal;
for (x = 0; x < NBYTES; x++)
{
octet[x] = (ipAddress >> (x * 8)) & (uint8)-1;
}
for (x = NBYTES - 1; x >= 0; --x)
{
if (NBYTES==4)
{
const char *IPPart = octet[x]; // HERE IS THE BUG!!!!! ?
strcpy(ipAddressFinal, IPPart);
}
else
{
const char *IPPart = octet[x]; // HERE IS THE BUG!!!!! ?
strcat(ipAddressFinal, IPPart);
}
if (x > 0)
strcat(ipAddressFinal, ".");
}
LogAlways("IP: %s", ipAddressFinal);
}
编辑
谢谢大家 - 问题已解决!感谢所有人!在短时间内得到非常好的答案真是太棒了!特别感谢Lacrymology!!!这里是现在正在运行的代码,我没有使用Linux,应该把我的操作系统等信息写下来...
if (ipAddress)
{
const int NBYTES = 4;
uint8 octet[NBYTES];
char ipAddressFinal[16];
for(int i = 0 ; i < NBYTES ; i++)
{
octet[i] = ipAddress >> (i * 8);
}
sprintf(ipAddressFinal, "%d.%d.%d.%d", octet[3], octet[2], octet[1], octet[0]);
LogAlways("IP: \"%s\"", ipAddressFinal);
}
ipAddressFinal[]
只分配了 15 个字节,但是考虑到空终止符,它应该有 16 个字节。每个字段最多有 3 个字符,所以 3 + 1 + 3 + 1 + 3 + 1 + 3 + 1 = 16。我已经修改了它,以便复制和粘贴的人不会传播这个错误。 - Mark Lakata