PHP和js对ip地址排序,要求转成无符号整数
时间: 2024-02-28 22:57:33 浏览: 26
首先,PHP可以使用`ip2long()`函数将IP地址转换为无符号整数。然后可以使用PHP的`usort()`函数对IP地址列表进行排序。
示例代码:
```php
// IP地址列表
$ips = ['192.168.1.1', '10.0.0.1', '172.16.0.1'];
// 将IP地址转换为无符号整数并排序
usort($ips, function ($a, $b) {
return ip2long($a) - ip2long($b);
});
// 输出排序后的IP地址列表
foreach ($ips as $ip) {
echo $ip . "\n";
}
```
对于JavaScript,可以先将IP地址转换为32位二进制数,然后再将其转换为无符号整数,并使用JavaScript的`sort()`函数对IP地址列表进行排序。
示例代码:
```javascript
// IP地址列表
var ips = ['192.168.1.1', '10.0.0.1', '172.16.0.1'];
// 将IP地址转换为32位二进制数并排序
ips.sort(function (a, b) {
var aBinary = '';
a.split('.').forEach(function (octet) {
aBinary += ('00000000' + parseInt(octet, 10).toString(2)).substr(-8);
});
var bBinary = '';
b.split('.').forEach(function (octet) {
bBinary += ('00000000' + parseInt(octet, 10).toString(2)).substr(-8);
});
return parseInt(aBinary, 2) - parseInt(bBinary, 2);
});
// 输出排序后的IP地址列表
ips.forEach(function (ip) {
console.log(ip);
});
```