Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit724ff7e

Browse files
committed
Add Hexadecimal to binary conversion
1 parentccf5065 commit724ff7e

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
packagecom.conversions;
2+
3+
publicclassHexadecimalToBinary {
4+
/**
5+
* This method converts a hexadecimal number to
6+
* a binary number.
7+
*
8+
* @param hexStr The hexadecimal number
9+
* @return The binary number
10+
*/
11+
12+
publicStringhexToBin (StringhexStr) {
13+
14+
StringbinaryString ="",hexaNumbers ="0123456789ABCDEF";
15+
intindexOfHex,decimalNumber =0,k =1;
16+
charletter;
17+
intbinaryArray[] =newint [50];
18+
19+
hexStr =hexStr.toUpperCase();
20+
21+
/**
22+
* Transform the hexadecimal number to decimal number
23+
*/
24+
for (inti =0 ;i <hexStr.length();i++) {
25+
letter =hexStr.charAt(i);
26+
indexOfHex =hexaNumbers.indexOf(letter);
27+
decimalNumber =16 *decimalNumber +indexOfHex;
28+
}
29+
30+
/**
31+
* Transform decimal number to binary and put it in an array
32+
*/
33+
while (decimalNumber !=0) {
34+
binaryArray[k++] =decimalNumber %2;
35+
decimalNumber =decimalNumber /2;
36+
}
37+
/**
38+
* Put the binary in a string
39+
*/
40+
for (intj =k-1 ;j>0 ;j--) {
41+
binaryString =binaryString +binaryArray[j];
42+
}
43+
44+
returnbinaryString;
45+
46+
}
47+
48+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
packagecom.conversions;
2+
3+
importstaticorg.junit.jupiter.api.Assertions.*;
4+
5+
importorg.junit.jupiter.api.Assertions;
6+
importorg.junit.jupiter.api.Test;
7+
8+
classHexadecimalToBinaryTest {
9+
10+
@Test
11+
voidtest() {
12+
HexadecimalToBinaryhexadecimalToBinary =newHexadecimalToBinary();
13+
Assertions.assertEquals("10101011",hexadecimalToBinary.hexToBin("AB"),"Incorrect Conversion");
14+
Assertions.assertEquals("10101101010101111001101",hexadecimalToBinary.hexToBin("56ABCD"),"Incorrect Conversion");
15+
Assertions.assertEquals("10011101111011010001001",hexadecimalToBinary.hexToBin("4ef689"),"Incorrect Conversion");
16+
Assertions.assertEquals("10011101111",hexadecimalToBinary.hexToBin("4EF"),"Incorrect Conversion");
17+
Assertions.assertEquals("101010111100110111101111",hexadecimalToBinary.hexToBin("ABCDEF"),"Incorrect Conversion");
18+
//It returns -1 if you enter a wrong hexaDecimal
19+
Assertions.assertEquals("-1",hexadecimalToBinary.hexToBin("K"),"Incorrect Conversion");
20+
}
21+
22+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp