package com.bobo.algorithm;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* User: bobo
* Date: 2019/11/29
* Description: ipv6 :"FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"
* 特点:使用8组16进制的数表示,每组占16位
* 每个16进制的f代表15,15在2进制中是1111,因此16进制每位对应二进制的4位
*
* 参考: https://www.cnblogs.com/heqiyoujing/p/10687741.html
*/
public class HandlerIpv6 {
public static void main(String[] args) {
System.out.println(Integer.toHexString(255));//0xff
//16进制转long
System.out.println(Long.parseLong("ff",16));
//String str = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
//String str = "0:0:0:0:0:0:0:0";
String str = "FFFF:FFFF:7654:FEDA:1245:BA98:3210:4562";
long[] longs = ip2LongArr(str);
String s = longArr2Ipv6(longs);
System.out.println(s);
}
public static long[] ip2LongArr(String string){
if (string==null || string.trim().isEmpty()) {
throw new IllegalArgumentException("input param is Invalid");
}
long[] arr= new long[2];
String[] split = string.split(":");
if (split.length != 8) {
throw new IllegalArgumentException();
}
for (int i = 0; i < 8; i++) {
String curr = split[i];
long l = Long.parseLong(curr, 16);
//每组16位
long l1 = l << (i * 16);
//每个 long 保存四组,i >> 2 = i / 4
// a|=b的意思就是把a和b按位或然后赋值给a 按位或的意思就是先把a和b都换成2进制,然后用或操作,相当于a=a|b
arr[i>>2] |=l1;
}
return arr;
}
public static String longArr2Ipv6(long[] arr){
if (arr == null || arr.length != 2) {
throw new IllegalArgumentException(Arrays.toString(arr) +"is not a vaild array");
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 2; i++) {
long l = arr[i];
for (int j = 0; j < 4; j++) {
long temp = (l >> (j * 16)) & 0xffff;
stringBuilder.append(":").append(Long.toString(temp,16));
}
}
return stringBuilder.substring(1).toString();
}
}
没有考虑大小写的转换。