Skip to content

Instantly share code, notes, and snippets.

@chiro-hiro
Last active August 20, 2023 16:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chiro-hiro/ee336cacf8e76635de821fa38b1bf526 to your computer and use it in GitHub Desktop.
Save chiro-hiro/ee336cacf8e76635de821fa38b1bf526 to your computer and use it in GitHub Desktop.
Unsigned 32 bits IP address to string
/*
g++ -std=c++11 ip2str.cpp -o ip2str
ip2str 0xb01a8c0 0x100007f
*/
#include <sstream>
#include <iostream>
using namespace std;
/* Simplest version */
string ipToStr2(uint32_t ip)
{
stringstream ipStr;
ipStr << (ip & 0xff) << ".";
ipStr << ((ip >>8) & 0xff) << ".";
ipStr << ((ip >>16) & 0xff) << ".";
ipStr << ((ip >>24) & 0xff);
return ipStr.str();
}
/* Shorter version */
string ipToStr(uint32_t ip)
{
stringstream ipStr;
for(short c = 0; c <= 24; c += 8){
ipStr << ((ip >> c) & 0xff) << ((c < 24) ? "." : "");
}
return ipStr.str();
}
int main(int argc, char* argv[])
{
string buf;
if(argc > 1){
for(int c = 1; c < argc; c++){
try{
buf.assign(argv[c]);
uint32_t a =stoul(buf, nullptr, 0);
cout << c << ": " << argv[c] << "(" << a << ") IP:" << ipToStr(a) << "\n";
}catch(...){
cout << c << ": Error at \"" << argv[c] << "\"\n";
}
}
}else{
cout << "Convert 32 bits to IP address string\nUsage: ip2str 0xb01a8c0 0x100007f\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment