Skip to content

Commit b26b8f4

Browse files
committed
Updated DecimalToHexaDecimal.java
1 parent cda4b5c commit b26b8f4

File tree

1 file changed

+26
-29
lines changed

1 file changed

+26
-29
lines changed

Conversions/DecimalToHexaDecimal.java

+26-29
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,30 @@
1-
import java.lang.StringBuilder;
2-
import java.util.Scanner;
31

4-
class Test {
5-
private static final int sizeOfIntInHalfBytes = 8;
6-
private static final int numberOfBitsInAHalfByte = 4;
7-
private static final int halfByte = 0x0F;
8-
private static final char[] hexDigits = {
9-
'0', '1', '2', '3', '4', '5', '6', '7',
10-
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
11-
};
2+
class DecimalToHexaDecimal {
3+
private static final int sizeOfIntInHalfBytes = 8;
4+
private static final int numberOfBitsInAHalfByte = 4;
5+
private static final int halfByte = 0x0F;
6+
private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
7+
'F' };
128

13-
public static String decToHex(int dec) {
14-
StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
15-
hexBuilder.setLength(sizeOfIntInHalfBytes);
16-
for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
17-
{
18-
int j = dec & halfByte;
19-
hexBuilder.setCharAt(i, hexDigits[j]);
20-
dec >>= numberOfBitsInAHalfByte;
21-
}
22-
return hexBuilder.toString();
23-
}
9+
// Returns the hex value of the dec entered in the parameter.
10+
public static String decToHex(int dec) {
11+
StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
12+
hexBuilder.setLength(sizeOfIntInHalfBytes);
13+
for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) {
14+
int j = dec & halfByte;
15+
hexBuilder.setCharAt(i, hexDigits[j]);
16+
dec >>= numberOfBitsInAHalfByte;
17+
}
18+
return hexBuilder.toString().toLowerCase();
19+
}
2420

25-
public static void main(String[] args) {
26-
Scanner sc = new Scanner(System.in);
27-
System.out.println("Write your Number to convert into HexaDecimal: ")
28-
int dec = 305445566;
29-
String hex = Integer.toHexString(dec);
30-
String hex = decToHex(dec);
31-
System.out.println(hex);
32-
}
21+
// Test above function.
22+
public static void main(String[] args) {
23+
System.out.println("Test...");
24+
int dec = 305445566;
25+
String libraryDecToHex = Integer.toHexString(dec);
26+
String decToHex = decToHex(dec);
27+
System.out.println("Result from the library : " + libraryDecToHex);
28+
System.out.println("Result decToHex method : " + decToHex);
29+
}
3330
}

0 commit comments

Comments
 (0)