【面试】ip地址转化为整数——位运算以及文件输入输出流

ip地址转化为整数

#include 
#include 
#include 

// 函数将IP地址字符串转换为整数
uint32_t ipToUint(const std::string& ip) {
    std::vector<int> parts;
    std::istringstream iss(ip);
    std::string part;
    while (std::getline(iss, part, '.')) {
        parts.push_back(std::stoi(part));
    }
    if (parts.size() != 4) {
        throw std::invalid_argument("Invalid IP address format");
    }
    return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3];
}

int main() {
    std::string ip = "192.168.1.1";
    uint32_t ipInt = ipToUint(ip);
    std::cout << "IP Address: " << ip << " => Integer: " << ipInt << std::endl;
    return 0;
}

整数转化为ip地址

#include 
#include 
#include 

// 函数将整数转换为IP地址字符串
std::string uintToIp(uint32_t ipInt) {
    std::ostringstream oss;
    oss << ((ipInt >> 24) & 0xFF) << '.' << ((ipInt >> 16) & 0xFF) << '.'
        << ((ipInt >> 8) & 0xFF) << '.' << (ipInt & 0xFF);
    return oss.str();
}

int main() {
    uint32_t ipInt = 3232235777; // 对应于IP地址 "192.168.1.1"
    std::string ip = uintToIp(ipInt);
    std::cout << "Integer: " << ipInt << " => IP Address: " << ip << std::endl;
    return 0;
}

你可能感兴趣的:(tcp/ip,网络协议,网络)