JAVA实现二进制和16进制之间的互相转换,8进制同理,附带异或操作实现
public static String bin2Hex(String binStr) { int deci = Integer.valueOf(binStr,2); return Integer.toHexString(deci); } public static String hex2Bin(String hexStr) { int deci = Integer.valueOf(hexStr,16); return Integer.toBinaryString(deci); }
public static void main(String args[]) { String str = "f012"; System.out.println(hex2Bin(str)); System.out.println(bin2Hex("01011011")); }
运行结果:
1111000000010010
5b
很easy
8进制同理,转换
可是以上方法的缺陷是,16进制或2进制串非常大时就转换失败,以下给出通用方法:
public static String bin2Hex(String binStr) { StringBuffer temp = null; while (binStr.length() % 4 != 0) { temp = new StringBuffer(binStr); temp.insert(0, "0"); binStr = temp.toString(); } StringBuffer sb = new StringBuffer(); int deci = 0; for (int i = 0; i <= binStr.length() - 4; i += 4) { deci = Integer.valueOf(binStr.substring(i, i + 4), 2); sb.append(Integer.toHexString(deci)); } return sb.toString(); }
public static String hex2Bin(String hexStr) { StringBuffer sb = new StringBuffer(); int deci = 0; StringBuffer temp = null; for (int i = 0; i < hexStr.length(); i++) { deci = Integer.valueOf(hexStr.charAt(i) + "", 16); temp = new StringBuffer(Integer.toBinaryString(deci)); while (temp.length() < 4) { temp.insert(0, "0"); } sb.append(temp); } return sb.toString(); }
顺带来个异或操作:
public static String xor(String binStr1, String binStr2) { int len1 = binStr1.length(); int len2 = binStr2.length(); StringBuffer sb = new StringBuffer(); if (len1 != len2) { return null; } for (int i = 0; i < len1; i++) { if (binStr1.charAt(i) == binStr2.charAt(i)) { sb.append("0"); } else { sb.append("1"); } } return sb.toString(); }
public static void main(String args[]) { String str = "89451211512131"; String str2 = "fd589213165131"; String bin1 = hex2Bin(str); String bin2 = hex2Bin(str2); System.out.println(bin1.length() + "==" + bin2.length()); System.out.println(bin2Hex(bin1)); System.out.println(bin2Hex(bin2)); String bin = xor(bin1,bin2); System.out.println(bin2Hex(bin)); }执行结果例如以下:
56==56
89451211512131
fd589213165131
741d8002477000
上述原理仍然是使用Integer.valueOf方法来实现的,仅仅只是是分段转换