Salve gente, provavo a risolvere questa sfida qua in C++, quella sotto è la mia soluzione (corretta), ma visto che non sono tanto pratico di "bitwise operations", giusto per curiosità mi domandavo se c'era qualche punto dove potevo ottimizzare il codice in maniera ovvia :P
input string:
output string:
input string:
"128.42.5.4/21"
C:
std::string calculateNetworkAddress(std::string cidr) {
//build networkMask
int maskVal = stoi(string(cidr.begin() + cidr.find('/') + 1,
cidr.end()));
uint32_t networkMask{};
for (int i = 31; i > 31 - maskVal; i--) {
networkMask |= 1 << i;
}
//extract IP digits
vector<uint8_t> IP;
auto begin = cidr.begin(), end = cidr.begin();
while (end != cidr.end())
{
if (!isdigit(*end)) {
int n = stoi(string(begin, end));
IP.push_back(n);
begin = end + 1;
}
end++;
}
//add together the bits of the 4 bytes representing the IP
uint32_t networkAddressVal{};
for (size_t i = 0; i < 4; i++){
networkAddressVal |= IP[i] << (3 - i)*8;
}
//[Logical AND] between IP bits and mask bits
networkAddressVal &= networkMask;
//extract new ip number from networkAddress bits
string result;
for (size_t i = 0; i < 4; i++) {
uint8_t val = {};
val |= networkAddressVal >> 8*(3-i);
result += to_string(val);
if (i < 3) { result += '.'; }
}
return result;
}
output string:
"128.42.0.0"
Ultima modifica: