作用:
Netmask:255.255.255.0
互转
Prefix:24
新实现:
static int NetmaskToPrefix(unsigned char* bytes, int bytes_size) noexcept {
if (NULL == bytes || bytes_size < 1) {
return 0;
}
int prefix = 0;
for (int i = 0; i < bytes_size; i++) {
int b = bytes[i];
while (b) {
prefix += b & 1;
b >>= 1;
}
}
return prefix;
}
源实现:
static UInt32 PrefixToNetmask(int prefix) noexcept {
UInt32 mask = prefix ? (-1L << (32L - prefix)) : 0L;
return htonl(mask);
}
static int NetmaskToPrefix(UInt32 mask) noexcept {
return NetmaskToPrefix(reinterpret_cast<unsigned char*>(&mask), sizeof(mask));
}
static int NetmaskToPrefix(unsigned char* bytes, int bytes_size) noexcept {
int bitLength = 0;
int idx = 0;
if (NULL == bytes || bytes_size < 0) {
return bitLength;
}
// find beginning 0xFF
for (; idx < bytes_size && bytes[idx] == 0xff; idx++);
bitLength = 8 * idx;
if (idx < bytes_size) {
switch (bytes[idx]) {
case 0xFE: bitLength += 7; break;
case 0xFC: bitLength += 6; break;
case 0xF8: bitLength += 5; break;
case 0xF0: bitLength += 4; break;
case 0xE0: bitLength += 3; break;
case 0xC0: bitLength += 2; break;
case 0x80: bitLength += 1; break;
case 0x00: break;
default: // invalid bitmask
return ~0;
}
// remainder must be 0x00
for (int j = idx + 1; j < bytes_size; j++) {
unsigned char x = bytes[j];
if (x != 0x00) {
return ~0;
}
}
}
return bitLength;
}