我需要从ip地址生成唯一的ID(字符串),反之亦然。唯一Id必须为8-9个字符。在java中有没有可以做到这一点的has函数?
发布于 2017-04-06 15:55:46
由于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( "." ) );
}
https://stackoverflow.com/questions/43248866
复制相似问题