Created
June 20, 2019 09:57
-
-
Save erwinv/682a071f73051bfa4789e933de9f25bd to your computer and use it in GitHub Desktop.
Netmask from subnet size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdint> | |
#include <optional> | |
#include <string> | |
std::optional<std::string> getNetMaskFromSubnetSize(uint64_t subnetSize) | |
{ | |
auto isPowerOf2 = [](uint64_t num) { return num > 0 and (num & (num - 1)) == 0; }; | |
if (not isPowerOf2(subnetSize)) | |
return std::nullopt; | |
// 64 bits because "0.0.0.0" subnet size is greater than numeric_limits<uint32_t>::max() | |
uint64_t bits = ~(subnetSize - 1); | |
return std::to_string((bits & 0xFF000000) >> 24) + "." | |
+ std::to_string((bits & 0x00FF0000) >> 16) + "." | |
+ std::to_string((bits & 0x0000FF00) >> 8) + "." | |
+ std::to_string((bits & 0x000000FF) >> 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment