It converts a Uint32-IP-address (like used by SDLNet) to a std::string. I used it in a messenger to display "* nick [192.168.0.x] connected" in the console and GUI (TTF).
It's pretty easy if you know how an IP is built up and you can calculate a bit in hex. For those who can't do that, I'll explain it shortly
An IP consists of 4 * 1 Byte with '.' inbetween (e.g. 127.0.0.1). A hex number takes 4 bits (a half byte). So you just isolate the last two hexadecimal digits of the Uint32 and you get a byte of the address. Then you convert it to ASCII, reverse it (wrong direction due to string adding!) and add it to a string. You do that until there are no digits left in the Uint32. The string is finally returned.
Code: Select all
string ConvertIP (Uint32 hexip)
{
Uint32 byte, intbuffer, digit;
string buffer, stringip;
string::reverse_iterator i;
while (hexip > 0) // run until there are no digits left
{
byte = hexip % 0x100; // get last two digits (1 Byte)
hexip /= 0x100; // cut the last two digits off
intbuffer = byte; // make a copy of the byte
buffer.clear (); // clear the string
do // now convert it to ASCII
{
digit = intbuffer % 10; // store last digit
intbuffer /= 10; // cut off last digit
buffer += digit + 48; // add '0' to get ASCII-values
} while (intbuffer > 0); // run until there are no digits left in the byte
for (i = buffer.rbegin (); i != buffer.rend (); ++i) // reverse the string
stringip += *i;
if (hexip > 0) // add a '.' if it is not the end of the IP
stringip += '.';
}
return stringip; // return the string
}