【发布时间】:2015-07-09 22:09:03
【问题描述】:
我正在尝试将字符串转换为 IP 地址。输入字符串是转换为std::string 的无符号整数,例如"123456"。
下面的代码不正确,因为它会产生不可读的二进制字符。
std::string str2IP(const std::string& address)
{
uint32_t ip = std::strtoul(address.c_str(), NULL, 0);
unsigned char bytes[4];
bytes[0] = ip & 0xFF;
bytes[1] = (ip >> 8) & 0xFF;
bytes[2] = (ip >> 16) & 0xFF;
bytes[3] = (ip >> 24) & 0xFF;
std::stringstream ss;
ss << bytes[3] << "." << bytes[2] << "." << bytes[1] << "." << bytes[0];
return ss.str();
}
【问题讨论】:
-
什么输出你得到什么输入?您对该输入的期望输出是什么? (另外,你为什么要输出字符?)
标签: c++ string type-conversion