File tree Expand file tree Collapse file tree
main/java/com/conversions
test/java/com/conversions Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .conversions ;
2+
3+ public class HexadecimalToBinary {
4+ /**
5+ * This method converts a hexadecimal number to
6+ * a binary number.
7+ *
8+ * @param hexStr The hexadecimal number
9+ * @return The binary number
10+ */
11+
12+ public String hexToBin (String hexStr ) {
13+
14+ String binaryString = "" , hexaNumbers = "0123456789ABCDEF" ;
15+ int indexOfHex , decimalNumber = 0 , k = 1 ;
16+ char letter ;
17+ int binaryArray [] = new int [50 ];
18+
19+ hexStr = hexStr .toUpperCase ();
20+
21+ /**
22+ * Transform the hexadecimal number to decimal number
23+ */
24+ for ( int i = 0 ; i < hexStr .length (); i ++) {
25+ letter = hexStr .charAt (i );
26+ indexOfHex = hexaNumbers .indexOf (letter );
27+ decimalNumber = 16 * decimalNumber + indexOfHex ;
28+ }
29+
30+ /**
31+ * Transform decimal number to binary and put it in an array
32+ */
33+ while (decimalNumber != 0 ) {
34+ binaryArray [k ++] = decimalNumber % 2 ;
35+ decimalNumber = decimalNumber / 2 ;
36+ }
37+ /**
38+ * Put the binary in a string
39+ */
40+ for ( int j = k -1 ; j >0 ; j --) {
41+ binaryString = binaryString + binaryArray [j ];
42+ }
43+
44+ return binaryString ;
45+
46+ }
47+
48+ }
Original file line number Diff line number Diff line change 1+ package com .conversions ;
2+
3+ import static org .junit .jupiter .api .Assertions .*;
4+
5+ import org .junit .jupiter .api .Assertions ;
6+ import org .junit .jupiter .api .Test ;
7+
8+ class HexadecimalToBinaryTest {
9+
10+ @ Test
11+ void test () {
12+ HexadecimalToBinary hexadecimalToBinary = new HexadecimalToBinary ();
13+ Assertions .assertEquals ("10101011" , hexadecimalToBinary .hexToBin ("AB" ), "Incorrect Conversion" );
14+ Assertions .assertEquals ("10101101010101111001101" , hexadecimalToBinary .hexToBin ("56ABCD" ), "Incorrect Conversion" );
15+ Assertions .assertEquals ("10011101111011010001001" , hexadecimalToBinary .hexToBin ("4ef689" ), "Incorrect Conversion" );
16+ Assertions .assertEquals ("10011101111" , hexadecimalToBinary .hexToBin ("4EF" ), "Incorrect Conversion" );
17+ Assertions .assertEquals ("101010111100110111101111" , hexadecimalToBinary .hexToBin ("ABCDEF" ), "Incorrect Conversion" );
18+ //It returns -1 if you enter a wrong hexaDecimal
19+ Assertions .assertEquals ("-1" , hexadecimalToBinary .hexToBin ("K" ), "Incorrect Conversion" );
20+ }
21+
22+ }
You can’t perform that action at this time.
0 commit comments