ip地址:string和int互转方案

思路:

ip范围是0~255,将每一段进行位运算,移8*(3-i)位就行了
转为string时8位一取即可
注意:需要使用unsigned int

#include <iostream>
#include <sstream>

extern std::string convert_address(unsigned int address);
extern unsigned int convert_address(std::string address);

int main()
{
    std::string tmpAddress = "192.168.3.9";
    unsigned int num = convert_address(tmpAddress);
    std::cout << "saveIP:" << num << std::endl;

	std::cout << "IP:" << convert_address(num);

    return 0;
}

// string to int 
unsigned int convert_address(std::string address) {
    unsigned int addrInt = 0;
    int i = 0;
    for (i = 0; i < 3; i++) {
        std::string::size_type npos = address.find(".");
        if (npos == std::string::npos) {
            break;
        }
        std::string value = address.substr(0, npos);
        unsigned int tmp = std::atoi(value.c_str());
        if ((tmp < 0) || (tmp > 255)) {
            break;
        }
        addrInt += tmp << ((3 - i) * 8);
        address = address.substr(npos + 1);
    }

    if (i != 3) {
        return 0;
    }
    int tmp = std::atoi(address.c_str());
    if ((tmp < 0) || (tmp > 255)) {
        return 0;
    }
    addrInt += tmp;
    return addrInt;
}
// int to string  
std::string convert_address(unsigned int address) {
    std::ostringstream stream;
    stream<<((address>>24) & 0xFF)<<"."<<((address>>16) & 0xFF)<<"."
    <<((address>>8) & 0xFF)<<"."<<(address & 0xFF);

    return stream.str();
}

saveIP:3232236297
IP:192.168.3.9
Process returned 0 (0x0)   execution time : 0.054 s
Press any key to continue.

ipAddress/gateway/dns都可以这样转

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值