将大整数转化成IP地址和把IP地址转化成大整数

来源:互联网 发布:侯佩岑情商评价知乎 编辑:程序博客网 时间:2024/04/27 15:17

#include <iostream>#include <vector>#include <string>using namespace std;typedef unsigned char uchar;void ulong2ip(unsigned int bignum){int mod_a = 0, num = 0, i = 0;int arr[8] = { 0 };while (bignum){mod_a = bignum % 16;arr[i++] = mod_a;bignum = bignum / 16;}for (num = 7; num>0; num--){cout << arr[num] << " ";printf("%x", arr[num]);}cout << endl;for (num = 7; num >0; num--, num--){cout << arr[num] * 16 + arr[num-1];if (num>1)cout << ".";}}void int2ipstr(unsigned  int ip) { printf("%u.%u.%u.%u", (uchar)* ((char *)&ip + 3), (uchar)* ((char *)&ip + 2), (uchar)* ((char *)&ip + 1), (uchar)* ((char *)&ip + 0)); }string ValueToIP(const int& nValue){//数值转化为IP//没有格式检查//返回值就是结果char strTemp[20];sprintf_s(strTemp, "%d.%d.%d.%d",(nValue & 0xff000000) >> 24,(nValue & 0x00ff0000) >> 16,(nValue & 0x0000ff00) >> 8,(nValue & 0x000000ff));return string(strTemp);}unsigned 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);        //a[3]=atoi(strtok(IP,'.').c_str());<pre code_snippet_id="1647425" snippet_file_name="blog_20160414_1_5934077" name="code" class="cpp">        //a[2]=atoi(strtok(NULL,'.').c_str());
        //a[1]=atoi(strtok(NULL,'.').c_str());
        //<span style="font-family: Arial, Helvetica, sans-serif;">a[0]=atoi(strtok(NULL,'\0').c_str());</span>

unsigned int nResult = (a[3] << 24) + (a[2] << 16) + (a[1] << 8) + a[0];return nResult;}int main(){unsigned int big_number = 0;char *buf;string strIP;cin >> big_number;ulong2ip(big_number);cout << endl;int2ipstr(big_number);cout << endl;cout << ValueToIP(big_number);cin >> strIP;cout << IPToValue(strIP);system("pause");return 0;}

0 0
原创粉丝点击