forked from TheAlgorithms/Java
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecimalToHexaDecimal.java
More file actions
Latest commit
30 lines (27 loc) · 1.07 KB
/
Copy pathDecimalToHexaDecimal.java
File metadata and controls
30 lines (27 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
classDecimalToHexaDecimal {
privatestaticfinalintsizeOfIntInHalfBytes = 8;
privatestaticfinalintnumberOfBitsInAHalfByte = 4;
privatestaticfinalinthalfByte = 0x0F;
privatestaticfinalchar[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F' };
// Returns the hex value of the dec entered in the parameter.
publicstaticStringdecToHex(intdec) {
StringBuilderhexBuilder = newStringBuilder(sizeOfIntInHalfBytes);
hexBuilder.setLength(sizeOfIntInHalfBytes);
for (inti = sizeOfIntInHalfBytes - 1; i >= 0; --i) {
intj = dec & halfByte;
hexBuilder.setCharAt(i, hexDigits[j]);
dec >>= numberOfBitsInAHalfByte;
}
returnhexBuilder.toString().toLowerCase();
}
// Test above function.
publicstaticvoidmain(String[] args) {
System.out.println("Test...");
intdec = 305445566;
StringlibraryDecToHex = Integer.toHexString(dec);
StringdecToHex = decToHex(dec);
System.out.println("Result from the library : " + libraryDecToHex);
System.out.println("Result decToHex method : " + decToHex);
}
}