Skip to content

Commit 6268d39

Browse files
committed
conversion binary to hexadecimal
1 parent e631e32 commit 6268d39

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package src.main.java.com.conversions;
2+
3+
import java.util.HashMap;
4+
5+
public class BinaryToHexadecimal {
6+
7+
/**
8+
* This method converts a binary number to
9+
* a hexadecimal number.
10+
*
11+
* @param binary The binary number
12+
* @return The hexadecimal number
13+
*/
14+
15+
public String binToHex(int binary) {
16+
//hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15
17+
HashMap<Integer,String> hmHexadecimal = new HashMap<>();
18+
19+
//String to store hexadecimal code
20+
String hex="";
21+
int i;
22+
for(i=0 ; i<10 ; i++)
23+
hmHexadecimal.put(i, String.valueOf(i));
24+
25+
for(i=10 ; i<16 ; i++)
26+
hmHexadecimal.put(i,String.valueOf((char)('A'+i-10)));
27+
28+
int currentbit;
29+
while(binary != 0) {
30+
int code4 = 0; //to store decimal equivalent of number formed by 4 decimal digits
31+
for(i=0 ; i<4 ; i++)
32+
{
33+
currentbit = binary % 10;
34+
binary = binary / 10;
35+
code4 += currentbit * Math.pow(2, i);
36+
}
37+
hex= hmHexadecimal.get(code4) + hex;
38+
}
39+
return hex;
40+
41+
}
42+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package src.test.java.com.conversions;
2+
3+
import org.junit.Test;
4+
import src.main.java.com.conversions.BinaryToHexadecimal;
5+
import org.junit.Assert;
6+
7+
public class BinaryToHexadecimalTest {
8+
9+
@Test
10+
public void testBinaryToHexadecimal(){
11+
BinaryToHexadecimal binaryToHexadecimal = new BinaryToHexadecimal();
12+
Assert.assertEquals("Incorrect Conversion", "2A", binaryToHexadecimal.binToHex(101010));
13+
Assert.assertEquals("Incorrect Conversion", "24", binaryToHexadecimal.binToHex(100100));
14+
}
15+
}

0 commit comments

Comments
 (0)