Skip to content

Commit

Permalink
Merge pull request TheAlgorithms#335 from LeeChungWan/master
Browse files Browse the repository at this point in the history
Updated DecimalToHexaDecimal.java
  • Loading branch information
varunu28 authored Dec 5, 2017
2 parents 6204a2d + b26b8f4 commit 3bfca30
Showing 1 changed file with 26 additions and 29 deletions.
55 changes: 26 additions & 29 deletions Conversions/DecimalToHexaDecimal.java
Original file line number Diff line number Diff line change
@@ -1,33 +1,30 @@
import java.lang.StringBuilder;
import java.util.Scanner;

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

public static String decToHex(int dec) {
StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
hexBuilder.setLength(sizeOfIntInHalfBytes);
for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
{
int j = dec & halfByte;
hexBuilder.setCharAt(i, hexDigits[j]);
dec >>= numberOfBitsInAHalfByte;
}
return hexBuilder.toString();
}
// Returns the hex value of the dec entered in the parameter.
public static String decToHex(int dec) {
StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
hexBuilder.setLength(sizeOfIntInHalfBytes);
for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) {
int j = dec & halfByte;
hexBuilder.setCharAt(i, hexDigits[j]);
dec >>= numberOfBitsInAHalfByte;
}
return hexBuilder.toString().toLowerCase();
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Write your Number to convert into HexaDecimal: ")
int dec = 305445566;
String hex = Integer.toHexString(dec);
String hex = decToHex(dec);
System.out.println(hex);
}
// Test above function.
public static void main(String[] args) {
System.out.println("Test...");
int dec = 305445566;
String libraryDecToHex = Integer.toHexString(dec);
String decToHex = decToHex(dec);
System.out.println("Result from the library : " + libraryDecToHex);
System.out.println("Result decToHex method : " + decToHex);
}
}

0 comments on commit 3bfca30

Please sign in to comment.