public static void main(String[] args) {
//二进制转10
int longip = binary2Decimal("00111011010000110000011001000000");
System.out.println(longip);
//10转ip
String privatestaticstringlongtoip = privatestaticstringlongtoip(longip);
System.out.println(privatestaticstringlongtoip);
}
public static String privatestaticstringlongtoip(int longip)
//将10进制整数形式转换成127.0.0.1形式的ip地址,在命令提示符下输入ping3396362403l
{
StringBuffer sb=new StringBuffer("");
sb.append(String.valueOf(longip>>>24));//直接右移24位
sb.append(".");
sb.append(String.valueOf((longip&0x00ffffff)>>>16));//将高8位置0,然后右移16位
sb.append(".");
sb.append(String.valueOf((longip&0x0000ffff)>>>8));
sb.append(".");
sb.append(String.valueOf(longip&0x000000ff));
sb.append(".");
return sb.toString();
}
/**
* 二进制转十进制
* @param number
* @return
*/
public static int binary2Decimal(String number) {
return scale2Decimal(number, 2);
}
/**
* 其他进制转十进制
* @param number
* @return
*/
public static int scale2Decimal(String number, int scale) {
checkNumber(number);
if (2 > scale || scale > 32) {
throw new IllegalArgumentException("scale is not in range");
}
// 不同其他进制转十进制,修改这里即可
int total = 0;
String[] ch = number.split("");
int chLength = ch.length;
for (int i = 0; i < chLength; i++) {
total += Integer.valueOf(ch[i]) * Math.pow(scale, chLength - 1 - i);
}
return total;
}
public static void checkNumber(String number) {
String regexp = "^\\d+$";
if (null == number || !number.matches(regexp)) {
throw new IllegalArgumentException("input is not a number");
}
}
https://www.jb51.net/article/32332.htm
https://www.jb51.net/article/32332.htm