C++子网掩码和数字互转

unsigned int MaskConvertToUint(const std::string &mask)
{
    unsigned int number = 0;
    unsigned int temp = 0;
    int count = 3;

    std::istringstream iss(mask);
    std::string token;

    while (std::getline(iss, token, '.'))
    {
        temp = std::stoi(token);
        number += temp << (count * 8);
        count--;
    }

    return number;
}

std::string UintConvertToMask(unsigned int num)
{
    std::stringstream ss;

    unsigned int mask = 0xFFFFFFFF << (32 - num);

    for (int i = 3; i >= 0; --i)
    {
        unsigned int octet = (mask >> (i * 8)) & 0xFF;
        ss << octet;

        if (i > 0)
            ss << ".";
    }

    return ss.str();
}

你可能感兴趣的:(c++,开发语言)