lotus

贵有恒何必三更眠五更起 最无益只怕一日曝十日寒

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. 题目

读题

HJ33 整数与IP地址间的转换 

 

考查点

 

2. 解法

思路

 二进制与十进制的互转

可参照   Java中十进制二进制相互转换的方法

代码逻辑

 

具体实现

 

public class IP2Num {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
System.out.println(convertIp10(sc.nextLine()));
System.out.println(convertIp(sc.nextLine()));
}
}


public static long convertIp10(String ip) {
String[] ips = ip.split("\\.");
StringBuffer sb = new StringBuffer();
for (String cur : ips) {
sb.append(binStr(cur));
}
return Long.parseLong(sb.toString(), 2);

}

private static String binStr(String s) {
StringBuffer sb = new StringBuffer();
int num = Integer.parseInt(s);
int k = 1 << 7;
for (int i = 0; i < 8; i++) {
int flag = (num & k) == 0 ? 0 : 1;
sb.append(flag);
num = num << 1;
}

return sb.toString();
}

public static String convertIp(String ip10) {
StringBuffer sb = new StringBuffer();
String ip2 = Long.toBinaryString(Long.parseLong(ip10));
String as = "";
for (int i = 0; i < 32 - ip2.length(); i++) {
as = as + "0";
}
ip2 = as + ip2;

for (int i = 0; i < ip2.length(); i = i + 8) {
sb.append(Long.parseLong(ip2.substring(i, i + 8), 2)).append(".");
}
return sb.deleteCharAt(sb.length() - 1).toString();
}

}

3. 总结

posted on 2023-07-19 20:03  白露~  阅读(69)  评论(0编辑  收藏  举报