将字符串转换为IP地址时输出错误

Wrong output when converting string to IP address

本文关键字:输出 错误 地址 IP 字符串 转换      更新时间:2023-10-16

我正在尝试将字符串转换为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();
}

I/O流的格式化输出函数(操作符<<)将char, signed charunsigned char视为字符—它们将值解释为字符代码,而不是数字。这段代码将输出A:

unsigned char c = 65;
std::cout << c;
在大多数实现中,std::uint8_t也是如此,因为它们只是将其用作typedefunsigned 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();
}

char s输出到std::stringstream具有输出由该char表示的编码字符而不是数字表示的语义。

您可以通过使用一元加号来强制使用数字表示来提升那些char s:

ss << +bytes[3] << "." << +bytes[2] << "." << +bytes[1] << "." << +bytes[0];