Java二进制转16进制**

从小数点开始,向左右二边按“四位一段”分段(不足补0),然后,每一段的四位二进制数就对应一位十六进制数。

public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		System.out.print("Enter a binary number: ");
		String binary = input.nextLine(); 
		
		binaryToHex(binary);
	}
	
	public static String binaryToHex(String binaryValue){
		//num得到该循环几次
		int num = binaryValue.length() / 4; 
		String sum_2 = " ";  
		//当字符串长度是4的倍数时
		if(binaryValue.length() % 4 == 0){
			//length使我们输出的结果是从左到右对应的
			int length = binaryValue.length() % 4;
			for (int i = 0; i < num ; i++) {
				int init = 0; 
				int sum = 0; 
				String letter = "";
				//s从左到右截取
				String s = binaryValue.substring(length, length + 4); 
				for (int m = s.length() - 1; m >= 0; m--) {  
					sum += (s.charAt(m) - 48) * Math.pow(2, init); 
					init ++; 
					//sum大于10以上要用A-F而不是数字
					switch(sum){
					case 10: letter = "A"; break;
					case 11: letter = "B"; break;
					case 12: letter = "C"; break;
					case 13: letter = "D"; break;
					case 14: letter = "E"; break;
					case 15: letter = "F"; break; 
					}
				} 
				length = length + 4;
				if(sum < 10)
					sum_2 += sum + "";
				else
					sum_2 += letter + "";
				
			}
			System.out.print("Hexadecimal value is " + sum_2);
		}
		//当字符串的长度不是4的倍数时
		else if(binaryValue.length() % 4 != 0){
			int length = binaryValue.length() % 4;
			for (int j = 0; j < num; j++) {
				int init = 0;
				int sum = 0; 
				String letter = "";
				String st = binaryValue.substring(length, length + 4); 
				System.out.print(st + " ");
				for (int n = st.length() - 1; n >= 0; n--) {
					sum += (st.charAt(n) - 48) * Math.pow(2, init); 
					init ++;
					switch(sum){
					case 10: letter = "A"; break;
					case 11: letter = "B"; break;
					case 12: letter = "C"; break;
					case 13: letter = "D"; break;
					case 14: letter = "E"; break;
					case 15: letter = "F"; break; 
					}
				}
				length = length + 4; 
				if(sum < 10)
					sum_2 += sum + "";
				else
					sum_2 += letter + "";
			}  
			int length_2 = binaryValue.length() % 4;
			int temp = 0;
			int c = 0;
			//左边剩下的不足4个的数字依然计算
				String str = binaryValue.substring(0, length_2 % 4);  
				for (int k = (length_2 % 4) - 1; k >= 0; k--) {
					temp += (str.charAt(k) - 48) * Math.pow(2, c);
					c++;
				}   
				System.out.print("Hexadecimal value is " + temp + "" + sum_2);
			}   
		return binaryValue;  
	} 

你可能感兴趣的:(Java二进制转16进制**)