实际中估计也没有这个需求,只是写写。
能不能直接由2进制转为16进制呢,最直接的办法是通过位移操作,也就是通常所说的 每四位二进制对应一个16进制,
假如java中有一种 二进制的基础类型 Binary bi = new Binary(11010101);这样的话 进行 bi >>> 4 位移操作 就可以很容易转换了,关于这个可以参考Integer.java中的toHexString(int i)方法.
但是没有这种类型,java中貌似没有直接转化的方法,也就只能先转为10进制,再转为16进制。
写下自己实现的比较笨的办法:
法1:和Integer源码中的进制转换在某些思路上类似
/**
* 10 0010 1111 按每4个一组分开,在binarys[]中找到对应的下标idx,对应的hexs[idx]相连接。
* @param binaryStr 10 0010 1111
* @return hexStr 22F
*/
public static String binaryToHex(String binaryStr){
String binarys[] = new String[]{
"0000","0001","0010","0011",
"0100","0101","0110","0111",
"1000","1001","1010","1011",
"1100","1101","1110","1111"
};
String hexs[] = new String[]{
"0","1","2","3",
"4","5","6","7",
"8","9","A","B",
"C","D","E","F"
};
int n = binaryStr.length()%4;
if(n != 0){
int zeroNum = 0;
zeroNum = 4 - n;
for(int i=0; i< zeroNum; i++){
binaryStr = "0"+binaryStr;
}
n = n+1;
}
String hexStr = "";
for(int j=0; j<binaryStr.length()/4; j++){
String temp = binaryStr.substring(j*4, (j+1)*4);
int index = -1;
for(int k=0;k<16;k++){
if(binarys[k].equals(temp)){
index = k;
}
}
if(index != -1){
hexStr = hexStr + hexs[index];
}
}
return hexStr;
}
法2:和法1只有一点区别
/**
* 10 0010 1111 按每4个一组分开,转化为int型数据index,然后hexs[index]相加。
* @param binaryStr 10 0010 1111
* @return hexStr 22F
*/
public static String binaryToHex2(String binaryStr){
String hexs[] = new String[]{
"0","1","2","3",
"4","5","6","7",
"8","9","A","B",
"C","D","E","F"
};
int n = binaryStr.length()%4;
if(n != 0){
int zeroNum = 0;
zeroNum = 4 - n;
for(int i=0; i< zeroNum; i++){
binaryStr = "0"+binaryStr;
}
n = n+1;
}
String hexStr = "";
for(int j=0; j<binaryStr.length()/4; j++){
String temp = binaryStr.substring(j*4, (j+1)*4);
int index =0;//下标 index=15,则对应输出 hexs[15] = F
int i = 3;
for(char c : temp.toCharArray()) {
String str = new String(new char[]{c});
index = index + ((Integer.parseInt(str))<<i) ;
i--;
}
hexStr = hexStr + hexs[index];
}
return hexStr;
}
上面的方法感觉执行效率不高,涉及到字符串的操作