IP与点分十进制数的字符串之间的转换(c++)
2014-09-04 13:13
302 查看
自己写的一个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 ;
}
#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 ;
}
相关文章推荐
- IP与点分十进制数的字符串之间的转换(c++)(转)
- 笔试:使用fprintf和sscanf 判断IP字符串的正确性和数字IP之间的转换
- 如何在字符串形式的IP和整数形式的IP之间转换呢?
- MySQL如何有效的存储IP地址及字符串IP和数值之间如何转换
- 如何:在各种字符串类型之间进行转换
- XML格式的字符串和DataSet之间的相互转换
- Visual C++ 如何:在各种字符串类型之间进行转换
- Visual C++ 如何:在各种字符串类型之间进行转换
- Unicode字符串与CString字符串之间的互相转换
- 在各种类型字符串之间转换
- 字符串与整数之间的转换(16进制)
- 字符串、PChar与字符数组之间的转换(delphi)
- java中字符串和时间之间的转换
- 16进制和字符串之间转换
- vb中字符串和其他类型之间的转换
- Visual C++ 如何:在各种字符串类型之间进行转换
- 字符串与二进制数之间的互相转换
- VC中实现多格式图像的灵活转换与字符串之间转换
- VC中一个关于宏的使用问题,字符串之间转换,宽字符与普通字符
- Visual C++ 如何:在各种字符串类型之间进行转换