Skip to content

Commit fe277cf

Browse files
authored
Merge pull request TheAlgorithms#694 from arodriguez33/Development
conversion binary to hexadecimal
2 parents e631e32 + 4f1fcee commit fe277cf

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package src.main.java.com.conversions;
2+
3+
import java.math.BigInteger;
4+
import java.util.HashMap;
5+
import java.util.Map;
6+
7+
8+
public class BinaryToHexadecimal {
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+
25+
/**
26+
* This method converts a binary number to
27+
* a hexadecimal number.
28+
*
29+
* @param binStr The binary number
30+
* @return The hexadecimal number
31+
*/
32+
33+
public String binToHex(String binStr) {
34+
BigInteger binary = new BigInteger(binStr);
35+
// String to store hexadecimal code
36+
String hex = "";
37+
38+
int currentBit;
39+
BigInteger tenValue = new BigInteger("10");
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();
45+
binary = binary.divide(tenValue);
46+
code4 += currentBit * Math.pow(2, i);
47+
}
48+
hex = hmHexadecimal.get(code4) + hex;
49+
}
50+
return hex;
51+
}
52+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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+
Assert.assertEquals("Incorrect Conversion", "AAAAAAAAAAAAAAAAAA1", binaryToHexadecimal.binToHex("1010101010101010101010101010101010101010101010101010101010101010101010100001"));
15+
}
16+
}

0 commit comments

Comments
 (0)