import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { int digitNumber=1; int sum = 0; String binary = "1110101011111010"; String hex; for(int i = 0; i < binary.length(); i++) { if(digitNumber == 1) sum += Integer.parseInt(binary.charAt(i) + "")*128; else if (digitNumber == 2) sum += Integer.parseInt(binary.charAt(i) + "")*64; else if (digitNumber == 3) sum += Integer.parseInt(binary.charAt(i) + "")*32; else if (digitNumber == 4) sum += Integer.parseInt(binary.charAt(i) + "")*16; else if (digitNumber == 5) sum += Integer.parseInt(binary.charAt(i) + "")*8; else if (digitNumber == 6) sum += Integer.parseInt(binary.charAt(i) + "")*4; else if (digitNumber == 7) sum += Integer.parseInt(binary.charAt(i) + "")*2; else if (digitNumber == 8) { sum += Integer.parseInt(binary.charAt(i) + "")*1; hex = Integer.toString(sum,16); System.out.print(hex); } else if (digitNumber == 9) { digitNumber = 1; sum=0; } digitNumber++; } } }
Hi everyone, I am trying to convert String of Binary to Hexadecimal. My string binary is “1110101011111010”. The output should be EAFA, but my output is EA7A. What’s wrong with my code? Can anybody help me, please?
Advertisement
Answer
In case you expect a long string
, you can use BigInteger
to convert any binary string to hexadecimal.
public static String convertBinaryToHexadecimal(String binaryStr) { return new BigInteger(binaryStr, 2).toString(16); }
Output:
BigInteger num = BigInteger.valueOf(Long.MAX_VALUE); String binaryStr = num.add(num).toString(2); // 2 times bigger than long System.out.println(convertBinaryToHexadecimal(binaryStr)); // fffffffffffffffe
public static String convertHexadecimalToBinary(String hexadecimalStr, int length) { return String.format("%0" + length + 'd', new BigInteger(new BigInteger(hexadecimalStr, 16).toString(2))); }
Output:
String hexadecimalStr = "7B"; System.out.println(convertHexadecimalToBinary(hexadecimalStr, 8)); // 01111011