java convert hex to binary method

Solutions on MaxInterview for java convert hex to binary method by the best coders in the world

showing results for - "java convert hex to binary method"
Dario
20 Feb 2020
1/**
2 * Method receives String hexadecimal value (of any range) and returns a String of a binary representation
3 * hexadecimal string format (ex.:"2FFA")
4 * Use of if-than-else statement inside for loop
5 * Use the Integer.toBinaryString(int i) method
6 */
7private String parseHexBinary(String hex) {
8		String digits = "0123456789ABCDEF";
9  		hex = hex.toUpperCase();
10		String binaryString = "";
11		
12		for(int i = 0; i < hex.length(); i++) {
13			char c = hex.charAt(i);
14			int d = digits.indexOf(c);
15			if(d == 0)	binaryString += "0000"; 
16			else  binaryString += Integer.toBinaryString(d);
17		}
18		return binaryString;
19	}
Andie
25 Mar 2020
1/**
2 * Method receives String hexadecimal value and returns a String of a binary representation
3 * hexadecimal string format (ex.:"2FFA")
4 * Only works with positive hexadecimal values (16xF does not work)
5 * Uses 2 for loops (hex -> dec & dec -> bin)
6 */
7private static int[] parseHexBinary(String hex) {
8		String digits = "0123456789ABCDEF";
9		int[] binaryValue = new int[hex.length()*4];
10		long val = 0;
11		
12		// convert hex to decimal
13		for(int i = 0; i < hex.length(); i++) {
14			char c = hex.charAt(i);
15			int d = digits.indexOf(c);
16			val = val*16 + d;
17		}
18		
19		// convert decimal to binary
20		for(int i = 0; i < binaryValue.length; i++) {
21			
22			binaryValue[i] = (int) (val%2);
23			val = val/2;
24		}
25		
26		return binaryValue;
27	}