将字符串转换为 IP 地址时输出错误
Wrong output when converting string to IP address
我正在尝试将字符串转换为 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();
}
将 char
s 输出到 std::stringstream
具有输出由 char
表示的编码字符而不是数字表示的语义。
您可以通过使用一元加号来强制数字表示来提升那些 char
s:
ss << +bytes[3] << "." << +bytes[2] << "." << +bytes[1] << "." << +bytes[0];
I/O 流的格式化输出函数(运算符 <<
)将 char
、signed char
和 unsigned char
视为 个字符——他们将值解释为字符代码,而不是数字。此代码将输出 A
:
unsigned char c = 65;
std::cout << c;
在大多数实现中,std::uint8_t
也是如此,因为它们只是将其用作 typedef
到 unsigned char
。您需要使用适当的数值类型,例如 unsigned short
:
std::string str2IP(const std::string& address)
{
uint32_t ip = std::strtoul(address.c_str(), NULL, 0);
unsigned short 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();
}
我正在尝试将字符串转换为 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();
}
将 char
s 输出到 std::stringstream
具有输出由 char
表示的编码字符而不是数字表示的语义。
您可以通过使用一元加号来强制数字表示来提升那些 char
s:
ss << +bytes[3] << "." << +bytes[2] << "." << +bytes[1] << "." << +bytes[0];
I/O 流的格式化输出函数(运算符 <<
)将 char
、signed char
和 unsigned char
视为 个字符——他们将值解释为字符代码,而不是数字。此代码将输出 A
:
unsigned char c = 65;
std::cout << c;
在大多数实现中,std::uint8_t
也是如此,因为它们只是将其用作 typedef
到 unsigned char
。您需要使用适当的数值类型,例如 unsigned short
:
std::string str2IP(const std::string& address)
{
uint32_t ip = std::strtoul(address.c_str(), NULL, 0);
unsigned short 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();
}