2

I'm trying to convert a string to IP address. The input string is an unsigned integer converted to std::string, for example "123456". The code below is not correct, as it produces unreadable binary characters.

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();
}
1
  • 2
    What output did you get for what input? What output did you expect for that input? (Also, why are you outputting characters?) Commented Jul 9, 2015 at 22:11

2 Answers 2

3

The formatted output functions (operator <<) of I/O streams treat char, signed char, and unsigned char as characters—they interpret the value as a character code, not as a number. This code will output A:

unsigned char c = 65;
std::cout << c;

The same holds for std::uint8_t on most implementations, because they just use it as a typedef to an unsigned char. You need to use a proper numerical type, such as 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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Outputting chars to a std::stringstream has the semantics of outputting the encoded character represented by that char rather than a numerical representation.

You can force numerical representation by using unary plus to promote those chars:

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

1 Comment

That will work. But that's not a good idea for nice readable portable/maintainable code. Change the type of bytes or explicitly cast them (static_cast) to make it obvious what your are doing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.