java convert hex to binary method

/**
 * Method receives String hexadecimal value (of any range) and returns a String of a binary representation
 * hexadecimal string format (ex.:"2FFA")
 * Use of if-than-else statement inside for loop
 * Use the Integer.toBinaryString(int i) method
 */
private String parseHexBinary(String hex) {
		String digits = "0123456789ABCDEF";
  		hex = hex.toUpperCase();
		String binaryString = "";
		
		for(int i = 0; i < hex.length(); i++) {
			char c = hex.charAt(i);
			int d = digits.indexOf(c);
			if(d == 0)	binaryString += "0000"; 
			else  binaryString += Integer.toBinaryString(d);
		}
		return binaryString;
	}

3.8
10
Toscanelli 80 points

                                    /**
 * Method receives String hexadecimal value and returns a String of a binary representation
 * hexadecimal string format (ex.:&quot;2FFA&quot;)
 * Only works with positive hexadecimal values (16xF does not work)
 * Uses 2 for loops (hex -&gt; dec &amp; dec -&gt; bin)
 */
private static int[] parseHexBinary(String hex) {
		String digits = &quot;0123456789ABCDEF&quot;;
		int[] binaryValue = new int[hex.length()*4];
		long val = 0;
		
		// convert hex to decimal
		for(int i = 0; i &lt; hex.length(); i++) {
			char c = hex.charAt(i);
			int d = digits.indexOf(c);
			val = val*16 + d;
		}
		
		// convert decimal to binary
		for(int i = 0; i &lt; binaryValue.length; i++) {
			
			binaryValue[i] = (int) (val%2);
			val = val/2;
		}
		
		return binaryValue;
	}

3.8 (10 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source