字符串与2进制互相转换,比较易于理解的一种方法
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String s1 = sc.nextLine(); String s2 = sc.nextLine(); String[] strs = s1.split("\\."); StringBuilder sb = new StringBuilder(); for(int i = 0;i<strs.length;i++) { int n = Integer.parseInt(strs[i]); String binary = Integer.toBinaryString(n); int len = binary.length(); for(int j = 0;j<8-len;j++){ binary = '0'+binary; } sb.append(binary); } long res1 = Long.parseLong(sb.toString(),2); System.out.println(res1); String s = Long.toBinaryString(Long.parseLong(s2)); int len = s.length(); for(int i = 0;i<32-len;i++){ s = '0'+s; } StringBuilder sb2 = new StringBuilder(); for(int i = 0;i<32;i=i+8){ String sub = s.substring(i,i+8); int n = Integer.parseInt(sub,2); sb2.append(n+"."); } String res2 = sb2.toString().substring(0,sb2.length()-1); System.out.println(res2); } } }