我需要从 IP 地址生成唯一 ID(字符串),反之亦然。唯一 ID 必须由 8-9 个字符组成。 java中有没有可以做到这一点的函数?
最佳答案
由于 IPv4 地址由 4 个字节组成,因此您可以简单地使用十六进制表示,这将导致 8 个字符
这可能是一个实现:
public static String ipToId(String ip) {
return Arrays.stream(ip.split("\\."))
.map(Integer::parseInt)
.map(number -> String.format("%02X", number))
.collect(Collectors.joining());
}
相反可以通过以下方式完成:
public static String idToIp( String id )
{
return Stream.of( id )
.map( Base64.getDecoder()::decode )
.flatMapToInt( bytes -> IntStream.range( 0, bytes.length )
.map( index -> bytes[index] & 0xFF ) )
.mapToObj( String::valueOf )
.collect( Collectors.joining( "." ) );
}
关于java - IP 地址的哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43248866/