[Interview] Convert IP address to integer - bit operations and file input and output streams

Convert ip address to integer

#include <iostream>
#include <sstream>
#include <vector>

// 函数将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;
}

Convert integer to ip address

#include <iostream>
#include <sstream>
#include <vector>

// 函数将整数转换为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;
}

Guess you like

Origin blog.csdn.net/weixin_36313227/article/details/133270823