题目:
HJ33 整数与IP地址间的转换
题解一:
ip转数字:
- ip按'.'分隔
- 分隔后逐位转换为二进制,不足8位首位补0
- 将2进制串再转换为十进制
数字转ip:
- 将数字转成二进制,不足32位首位补0
- 对32位二进制每8位截取,并转成十进制
- 用 '.' 连接十进制数字串
public String convertIpFromNumber(long number) {StringBuilder binary = new StringBuilder(toBinary(String.valueOf(number)));while (binary.length() < 32) {binary.insert(0, "0");}int step = 8;int left = 0;int right = 0;String binaryString = binary.toString();List<String> resultList = new ArrayList<>();while (right <= binaryString.length() - 1) {left = right;right += step;String substring = binaryString.substring(left, right);resultList.add(String.valueOf(toNumberByBinary(substring)));}return String.join(".", resultList);}public long convertNumberFromIp(String s) {StringBuilder stringBuilder = new StringBuilder();String[] split = s.split("\\.");for (String s1 : split) {stringBuilder.append(toBinary(s1));}return toNumberByBinary(stringBuilder.toString());}public long toNumberByBinary(String string) {long result = 0;int index = 0;char[] chars = string.toCharArray();for (int i = chars.length - 1; i >=0; i--) {int n = chars[i] - '0';result += n * Math.pow(2, index++);}return result;}public String toBinary(String number) {StringBuilder stringBuilder = new StringBuilder();long n = Long.parseLong(number);while (n != 0) {stringBuilder.append(n%2);n /= 2;}if (stringBuilder.length() < 8) {while (stringBuilder.length() != 8) {stringBuilder.append("0");}}return stringBuilder.reverse().toString();}
题解二:
IP中一个数字二进制占8位,4个数字占32位,2^32 = 256,所以IP可以当做256进制运算。
public String numberToIp(long number) {String[] resultArr = new String[4];for (int i = 3; i >= 0; i--) {resultArr[i] = String.valueOf(number%256);number /= 256;}return String.join(".", resultArr);}public long ipToNumber(String ip) {long result = 0;String[] split = ip.split("\\.");for (String s : split) {result = result*256 + Integer.parseInt(s);}return result;}