Merge pull request #335 from LeeChungWan/master

Updated DecimalToHexaDecimal.java
This commit is contained in:
Varun Upadhyay 2017-12-05 05:46:02 -08:00 committed by GitHub
commit 3bfca30e40
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,33 +1,30 @@
import java.lang.StringBuilder;
import java.util.Scanner;
class Test { class DecimalToHexaDecimal {
private static final int sizeOfIntInHalfBytes = 8; private static final int sizeOfIntInHalfBytes = 8;
private static final int numberOfBitsInAHalfByte = 4; private static final int numberOfBitsInAHalfByte = 4;
private static final int halfByte = 0x0F; private static final int halfByte = 0x0F;
private static final char[] hexDigits = { private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'0', '1', '2', '3', '4', '5', '6', '7', 'F' };
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
public static String decToHex(int dec) { // Returns the hex value of the dec entered in the parameter.
StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes); public static String decToHex(int dec) {
hexBuilder.setLength(sizeOfIntInHalfBytes); StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) hexBuilder.setLength(sizeOfIntInHalfBytes);
{ for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) {
int j = dec & halfByte; int j = dec & halfByte;
hexBuilder.setCharAt(i, hexDigits[j]); hexBuilder.setCharAt(i, hexDigits[j]);
dec >>= numberOfBitsInAHalfByte; dec >>= numberOfBitsInAHalfByte;
} }
return hexBuilder.toString(); return hexBuilder.toString().toLowerCase();
} }
public static void main(String[] args) { // Test above function.
Scanner sc = new Scanner(System.in); public static void main(String[] args) {
System.out.println("Write your Number to convert into HexaDecimal: ") System.out.println("Test...");
int dec = 305445566; int dec = 305445566;
String hex = Integer.toHexString(dec); String libraryDecToHex = Integer.toHexString(dec);
String hex = decToHex(dec); String decToHex = decToHex(dec);
System.out.println(hex); System.out.println("Result from the library : " + libraryDecToHex);
} System.out.println("Result decToHex method : " + decToHex);
}
} }