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

问题描述:

我试图将字符串转换为IP地址。输入字符串是一个转换为std::string的无符号整数,例如"123456"。 下面的代码不正确,因为它会产生不可读的二进制字符。将字符串转换为IP地址时输出错误

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

您输入了什么输出?你对这个输入有什么期望的输出? (另外,你为什么要输出字符?) –

1.4.3 char s到一个std::stringstream具有输出由char而非数值表示所表示的编码的字符的语义。

可以通过使用一元加号促进这些char s强制数值表示:

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

这将工作。但这对于可读性好的可移植/可维护代码来说并不是一个好主意。改变'bytes'的类型或者明确地强制转换它们(static_cast)以使它明显地表明你在做什么。 –

格式化的输出功能(操作者<<)I/O流治疗charsigned char,和unsigned 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(); 
}