IP與點分十進位制數的字串之間的轉換(c++)
阿新 • • 發佈:2019-02-04
自己寫的一個IP地址與點分十進位制數的字串之間的轉換的示列:
#include "stdafx.h" #include <iostream> #include <string> //#include <windows.h> using namespace std; int IPToValue(const string& strIP) { //IP轉化為數值 //沒有格式檢查 //返回值就是結果 int a[4]; string IP = strIP; string strTemp; size_t pos; size_t i=3; do { pos = IP.find("."); if(pos != string::npos) { strTemp = IP.substr(0,pos); a[i] = atoi(strTemp.c_str()); i--; IP.erase(0,pos+1); } else { strTemp = IP; a[i] = atoi(strTemp.c_str()); break; } }while(1); int nResult = (a[3]<<24) + (a[2]<<16)+ (a[1]<<8) + a[0]; return nResult; } string ValueToIP(const int& nValue) { //數值轉化為IP //沒有格式檢查 //返回值就是結果 char strTemp[20]; sprintf( strTemp,"%d.%d.%d.%d", (nValue&0xff000000)>>24, (nValue&0x00ff0000)>>16, (nValue&0x0000ff00)>>8, (nValue&0x000000ff) ); return string(strTemp); } int main(void) { //對於218.92.189.40轉化後-631456472 //cout<<hex<<-631456472 <<endl;//輸出da5cbd28 string strIP= "218.92.189.40"; cout<<dec<<IPToValue(strIP)<<endl; //cout<<hex<<IPToValue(strIP)<<endl; cout<<ValueToIP(-631456472)<<endl; //IP為:218.92.176.82轉化後 -631459758 strIP= "218.92.176.82"; cout<<dec<<IPToValue(strIP)<<endl; //cout<<hex<<IPToValue(strIP)<<endl; cout<<ValueToIP(-631459758)<<endl; return 0 ; }