I have a homework assignment where I need to do three-way conversion between decimal, binary and hexadecimal. The function I need help with is converting a decimal into a he
I need a function that takes in an int dec and returns a String hex.
I found a more elegant solution from http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html . I changed a bit from the original ( see the edit )
// precondition: d is a nonnegative integer
public static String decimal2hex(int d) {
String digits = "0123456789ABCDEF";
if (d <= 0) return "0";
int base = 16; // flexible to change in any base under 16
String hex = "";
while (d > 0) {
int digit = d % base; // rightmost digit
hex = digits.charAt(digit) + hex; // string concatenation
d = d / base;
}
return hex;
}
Disclaimer: I use this algorithm in my coding interview. I hope this solution doesn't get too popular :)
Edit June 17 2016 : I added the base variable to give the flexibility to change into any base : binary, octal, base of 7 ...
According to the comments, this solution is the most elegant so I removed the implementation of Integer.toHexString() .
Edit September 4 2015 : I found a more elegant solution http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html