|
| 1 | +package src.main.java.com.conversions; |
| 2 | + |
| 3 | +import java.math.BigInteger; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | + |
| 7 | + |
| 8 | +public class BinaryToHexadecimal { |
| 9 | + |
| 10 | + /** |
| 11 | + * hm to store hexadecimal codes for binary numbers |
| 12 | + * within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15 |
| 13 | + */ |
| 14 | + private static Map<Integer, String> hmHexadecimal = new HashMap<>(16); |
| 15 | + |
| 16 | + static { |
| 17 | + int i; |
| 18 | + for (i = 0; i < 10; i++) |
| 19 | + hmHexadecimal.put(i, String.valueOf(i)); |
| 20 | + |
| 21 | + for (i = 10; i < 16; i++) |
| 22 | + hmHexadecimal.put(i, String.valueOf((char) ('A' + i - 10))); |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * This method converts a binary number to |
| 27 | + * a hexadecimal number. |
| 28 | + * |
| 29 | + * @param binStr The binary number |
| 30 | + * @return The hexadecimal number |
| 31 | + */ |
| 32 | + |
| 33 | + public String binToHex(String binStr) { |
| 34 | + BigInteger binary = new BigInteger(binStr); |
| 35 | + // String to store hexadecimal code |
| 36 | + String hex = ""; |
| 37 | + |
| 38 | + int currentBit; |
| 39 | + BigInteger tenValue = new BigInteger("10"); |
| 40 | + while (binary.compareTo(BigInteger.ZERO) != 0) { |
| 41 | + // to store decimal equivalent of number formed by 4 decimal digits |
| 42 | + int code4 = 0; |
| 43 | + for (int i = 0; i < 4; i++) { |
| 44 | + currentBit = binary.mod(tenValue).intValueExact(); |
| 45 | + binary = binary.divide(tenValue); |
| 46 | + code4 += currentBit * Math.pow(2, i); |
| 47 | + } |
| 48 | + hex = hmHexadecimal.get(code4) + hex; |
| 49 | + } |
| 50 | + return hex; |
| 51 | + } |
| 52 | +} |
0 commit comments