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 hexadecimal. I have nearly no understanding of hexadecimal, nonetheless how to convert a decimal into hex. I need a function that takes in an int dec
and returns a String hex
. Unfortunately I don't have any draft of this function, I'm completely lost. All I have is this.
public static String decToHex(int dec)
{
String hex = "";
return hex;
}
Also I can't use those premade functions like Integer.toHexString() or anything, I need to actually make the algorithm or I wouldn't have learned anything.
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 )
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
Here's mine
Check out the code below for decimal to hexadecimal conversion,
You can learn more on different ways to convert decimal to hexadecimal in the following link >> java convert decimal to hexadecimal.
Here is the code for any number :
Consider dec2m method below for conversion from dec to hex, oct or bin.
Sample output is
28 dec == 11100 bin 28 dec == 34 oct 28 dec == 1C hex
Another possible solution: