2
2
3
3
import java .math .BigInteger ;
4
4
import java .util .HashMap ;
5
+ import java .util .Map ;
6
+
5
7
6
8
public class BinaryToHexadecimal {
7
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
+
8
25
/**
9
26
* This method converts a binary number to
10
27
* a hexadecimal number.
11
28
*
12
- * @param binary The binary number
29
+ * @param binStr The binary number
13
30
* @return The hexadecimal number
14
31
*/
15
32
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 = "" ;
19
37
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 ;
30
39
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 ();
36
45
binary = binary .divide (tenValue );
37
- code4 += currentbit * Math .pow (2 , i );
46
+ code4 += currentBit * Math .pow (2 , i );
38
47
}
39
- hex = hmHexadecimal .get (code4 ) + hex ;
48
+ hex = hmHexadecimal .get (code4 ) + hex ;
40
49
}
41
50
return hex ;
42
-
43
51
}
44
- }
52
+ }
0 commit comments