【问题标题】:Wrong output when converting string to IP address将字符串转换为 IP 地址时输出错误
【发布时间】: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


【解决方案1】:

I/O 流的格式化输出函数(运算符&lt;&lt;)将charsigned 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();
}

【讨论】:

    【解决方案2】:

    chars 输出到std::stringstream 的语义是输出由char 表示的编码字符,而不是数字表示。

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

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

    【讨论】:

    • 那行得通。但这对于可读性好的可移植/可维护代码来说不是一个好主意。更改 bytes 的类型或显式转换它们 (static_cast) 以明确您在做什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2019-05-13
    • 2023-03-05
    相关资源
    最近更新 更多