Skip to content

conversion binary to hexadecimal #694

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions src/main/java/com/conversions/BinaryToHexadecimal.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package src.main.java.com.conversions;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;


public class BinaryToHexadecimal {

/**
* hm to store hexadecimal codes for binary numbers
* within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15
*/
private static Map<Integer, String> hmHexadecimal = new HashMap<>(16);

static {
int i;
for (i = 0; i < 10; i++)
hmHexadecimal.put(i, String.valueOf(i));

for (i = 10; i < 16; i++)
hmHexadecimal.put(i, String.valueOf((char) ('A' + i - 10)));
}

/**
* This method converts a binary number to
* a hexadecimal number.
*
* @param binStr The binary number
* @return The hexadecimal number
*/

public String binToHex(String binStr) {
BigInteger binary = new BigInteger(binStr);
// String to store hexadecimal code
String hex = "";

int currentBit;
BigInteger tenValue = new BigInteger("10");
while (binary.compareTo(BigInteger.ZERO) != 0) {
// to store decimal equivalent of number formed by 4 decimal digits
int code4 = 0;
for (int i = 0; i < 4; i++) {
currentBit = binary.mod(tenValue).intValueExact();
binary = binary.divide(tenValue);
code4 += currentBit * Math.pow(2, i);
}
hex = hmHexadecimal.get(code4) + hex;
}
return hex;
}
}
16 changes: 16 additions & 0 deletions src/test/java/com/conversions/BinaryToHexadecimalTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package src.test.java.com.conversions;

import org.junit.Test;
import src.main.java.com.conversions.BinaryToHexadecimal;
import org.junit.Assert;

public class BinaryToHexadecimalTest {

@Test
public void testBinaryToHexadecimal(){
BinaryToHexadecimal binaryToHexadecimal = new BinaryToHexadecimal();
Assert.assertEquals("Incorrect Conversion", "2A", binaryToHexadecimal.binToHex("101010"));
Assert.assertEquals("Incorrect Conversion", "24", binaryToHexadecimal.binToHex("100100"));
Assert.assertEquals("Incorrect Conversion", "AAAAAAAAAAAAAAAAAA1", binaryToHexadecimal.binToHex("1010101010101010101010101010101010101010101010101010101010101010101010100001"));
}
}