Skip to content

Commit ccf5065

Browse files
committed
Add HexadecimalToDecimal conversion
1 parent f82bf1a commit ccf5065

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.conversions;
2+
3+
4+
public class HexadecimalToDecimal {
5+
6+
/**
7+
* This method converts a Hexadecimal number to a decimal number
8+
*
9+
* @param hexadecimalStr
10+
* @return decimal number
11+
*/
12+
public String hexToDecimal(String hexaStr) {
13+
String hexaNumbers = "0123456789ABCDEF";
14+
int m, result = 0;
15+
char letter;
16+
String decimalStr;
17+
hexaStr = hexaStr.toUpperCase();
18+
19+
for (int i = 0 ; i < hexaStr.length() ; i++) {
20+
/**
21+
* Letter will store the hexadecimal number as long as we loop through
22+
* the string
23+
*/
24+
letter = hexaStr.charAt(i);
25+
26+
/**
27+
* m is the index of the number that we are looping through in the
28+
* hexaNumbers
29+
*/
30+
m = hexaNumbers.indexOf(letter);
31+
result = 16*result + m;
32+
}
33+
34+
decimalStr = String.valueOf(result);
35+
return decimalStr ;
36+
}
37+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.conversions;
2+
3+
4+
import org.junit.jupiter.api.Assertions;
5+
import org.junit.jupiter.api.Test;
6+
7+
class HexadecimalToDecimalTest {
8+
9+
@Test
10+
void testHexadecimalToDecimalTest() {
11+
12+
HexadecimalToDecimal hexadecimalToDecimal = new HexadecimalToDecimal();
13+
Assertions.assertEquals("171", hexadecimalToDecimal.hexToDecimal("AB"), "Incorrect Conversion");
14+
Assertions.assertEquals("5680077", hexadecimalToDecimal.hexToDecimal("56ABCD"), "Incorrect Conversion");
15+
Assertions.assertEquals("5174921", hexadecimalToDecimal.hexToDecimal("4ef689"), "Incorrect Conversion");
16+
Assertions.assertEquals("1263", hexadecimalToDecimal.hexToDecimal("4EF"), "Incorrect Conversion");
17+
Assertions.assertEquals("11259375", hexadecimalToDecimal.hexToDecimal("ABCDEF"), "Incorrect Conversion");
18+
//It returns -1 if you enter a wrong hexaDecimal
19+
Assertions.assertEquals("-1", hexadecimalToDecimal.hexToDecimal("K"), "Incorrect Conversion");
20+
21+
}
22+
23+
}

0 commit comments

Comments
 (0)