Skip to content

Commit d082862

Browse files
authored
Update BinaryToHexadecimal.java
1 parent 6312a1e commit d082862

File tree

1 file changed

+31
-23
lines changed

1 file changed

+31
-23
lines changed

src/main/java/com/conversions/BinaryToHexadecimal.java

Lines changed: 31 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,43 +2,51 @@
22

33
import java.math.BigInteger;
44
import java.util.HashMap;
5+
import java.util.Map;
6+
57

68
public class BinaryToHexadecimal {
79

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+
825
/**
926
* This method converts a binary number to
1027
* a hexadecimal number.
1128
*
12-
* @param binary The binary number
29+
* @param binStr The binary number
1330
* @return The hexadecimal number
1431
*/
1532

16-
public String binToHex(BigInteger binary) {
17-
//hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15
18-
HashMap<Integer,String> hmHexadecimal = new HashMap<>();
33+
public String binToHex(String binStr) {
34+
BigInteger binary = new BigInteger(binStr);
35+
// String to store hexadecimal code
36+
String hex = "";
1937

20-
//String to store hexadecimal code
21-
String hex="";
22-
int i;
23-
for(i=0 ; i<10 ; i++)
24-
hmHexadecimal.put(i, String.valueOf(i));
25-
26-
for(i=10 ; i<16 ; i++)
27-
hmHexadecimal.put(i,String.valueOf((char)('A'+i-10)));
28-
29-
int currentbit;
38+
int currentBit;
3039
BigInteger tenValue = new BigInteger("10");
31-
while(binary.compareTo(BigInteger.ZERO) != 0) {
32-
int code4 = 0; //to store decimal equivalent of number formed by 4 decimal digits
33-
for(i=0 ; i<4 ; i++)
34-
{
35-
currentbit = binary.mod(tenValue).intValueExact();
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();
3645
binary = binary.divide(tenValue);
37-
code4 += currentbit*Math.pow(2, i);
46+
code4 += currentBit * Math.pow(2, i);
3847
}
39-
hex= hmHexadecimal.get(code4) + hex;
48+
hex = hmHexadecimal.get(code4) + hex;
4049
}
4150
return hex;
42-
4351
}
44-
}
52+
}

0 commit comments

Comments
 (0)