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

时间:2015-07-09 22:09:04

标签: c++ string type-conversion

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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

您可以使用一元加号强制数字表示来推广char s:

ss << +bytes[3] << "." << +bytes[2] << "." << +bytes[1] << "." << +bytes[0];
相关问题