字符串IP和数字转换的杂谈

long ip_to_value(const string& strIP)//低字节在后,高字节在前
{
    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);

    long nResult = (a[3]<<24) + (a[2]<<16)+ (a[1]<<8) + a[0];
    return nResult;
}
string value_to_ip(const long& nValue)
{
    char strTemp[20];
    sprintf( strTemp,"%ld.%ld.%ld.%ld",
        (nValue&0xff000000)>>24,
        (nValue&0x00ff0000)>>16,
        (nValue&0x0000ff00)>>8,
        (nValue&0x000000ff) );

    return string(strTemp);
}
inet_addr("255.255.255.0")//低字节在前,高字节在后
string test = "ffffffff";
long addr = strtoul(test.c_str(),0,16);//16进制数字的字符串转数字


你可能感兴趣的:(C/C++编程)