Add Hexadecimal to binary conversion

This commit is contained in:
MohamedBechir 2020-05-25 03:33:41 +01:00
parent ccf506514a
commit 724ff7ef30
2 changed files with 70 additions and 0 deletions

View File

@ -0,0 +1,48 @@
package com.conversions;
public class HexadecimalToBinary {
/**
* This method converts a hexadecimal number to
* a binary number.
*
* @param hexStr The hexadecimal number
* @return The binary number
*/
public String hexToBin (String hexStr) {
String binaryString = "", hexaNumbers = "0123456789ABCDEF";
int indexOfHex, decimalNumber = 0, k = 1;
char letter;
int binaryArray[] = new int [50];
hexStr = hexStr.toUpperCase();
/**
* Transform the hexadecimal number to decimal number
*/
for ( int i = 0 ; i < hexStr.length(); i++) {
letter = hexStr.charAt(i);
indexOfHex = hexaNumbers.indexOf(letter);
decimalNumber = 16 * decimalNumber + indexOfHex;
}
/**
* Transform decimal number to binary and put it in an array
*/
while (decimalNumber != 0) {
binaryArray[k++] = decimalNumber % 2;
decimalNumber = decimalNumber / 2;
}
/**
* Put the binary in a string
*/
for ( int j = k-1 ; j>0 ; j--) {
binaryString = binaryString + binaryArray[j];
}
return binaryString;
}
}

View File

@ -0,0 +1,22 @@
package com.conversions;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class HexadecimalToBinaryTest {
@Test
void test() {
HexadecimalToBinary hexadecimalToBinary = new HexadecimalToBinary();
Assertions.assertEquals("10101011", hexadecimalToBinary.hexToBin("AB"), "Incorrect Conversion");
Assertions.assertEquals("10101101010101111001101", hexadecimalToBinary.hexToBin("56ABCD"), "Incorrect Conversion");
Assertions.assertEquals("10011101111011010001001", hexadecimalToBinary.hexToBin("4ef689"), "Incorrect Conversion");
Assertions.assertEquals("10011101111", hexadecimalToBinary.hexToBin("4EF"), "Incorrect Conversion");
Assertions.assertEquals("101010111100110111101111", hexadecimalToBinary.hexToBin("ABCDEF"), "Incorrect Conversion");
//It returns -1 if you enter a wrong hexaDecimal
Assertions.assertEquals("-1", hexadecimalToBinary.hexToBin("K"), "Incorrect Conversion");
}
}