Answers for "java hex to binary to byte"

2

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;
	}
Posted by: Guest on December-22-2020
1

binary to hexadecimal in java

import java.util.Scanner;
public class BinaryToHexadecimalJava
{
   public static void main(String[] args)
   {
      int[] hexaDecimal = new int[1000];
      int a = 1, b = 0, r, decimal = 0, binary;
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter binary number: ");
      binary = sc.nextInt();
      while(binary > 0)
      {
         r = binary % 2;
         decimal = decimal + r * a;
         a = a * 2;
         binary = binary / 10;
      }
      a = 0;
      while(decimal != 0)
      {
         hexaDecimal[a] = decimal % 16;
         decimal = decimal / 16;
         a++;
      }
      System.out.print("Equivalent hexadecimal value is: ");
      for(b = a - 1; b >= 0; b--)
      {
         if(hexaDecimal[b] > 9)
         {
            System.out.print((char)(hexaDecimal[b] + 55) + "\n");
         }
         else
         {
            System.out.print(hexaDecimal[b] + "\n");
         }
      }
      sc.close();
   }
}
Posted by: Guest on October-30-2020
0

java convert hex to binary method

/**
 * Method receives String hexadecimal value and returns a String of a binary representation
 * hexadecimal string format (ex.:"2FFA")
 * Only works with positive hexadecimal values (16xF does not work)
 * Uses 2 for loops (hex -> dec & dec -> bin)
 */
private static int[] parseHexBinary(String hex) {
		String digits = "0123456789ABCDEF";
		int[] binaryValue = new int[hex.length()*4];
		long val = 0;
		
		// convert hex to decimal
		for(int i = 0; i < 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 < binaryValue.length; i++) {
			
			binaryValue[i] = (int) (val%2);
			val = val/2;
		}
		
		return binaryValue;
	}
Posted by: Guest on December-22-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language