# Java Data Type How to - Convert A Number To Hexadecimal

## Question

We would like to know how to convert A Number To Hexadecimal.

```public class Main {
public static String ConvertToHexadecimal(int num) {
int r;/* w w w. j av  a2s . c  om*/
String bin = "\0";
do {
r = num % 16;
num = num / 16;

if (r == 10)
bin = "A" + bin;

else if (r == 11)
bin = "B" + bin;

else if (r == 12)
bin = "C" + bin;

else if (r == 13)
bin = "D" + bin;

else if (r == 14)
bin = "E" + bin;

else if (r == 15)
bin = "F" + bin;

else
bin = r + bin;
} while (num != 0);

return bin;
}

public static int ConvertFromHexadecimalToDecimal(String num) {
int a;
int ctr = 0;
double prod = 0;

for (int i = num.length(); i > 0; i--) {

if (num.charAt(i - 1) == 'a' || num.charAt(i - 1) == 'A')
a = 10;

else if (num.charAt(i - 1) == 'b' || num.charAt(i - 1) == 'B')
a = 11;

else if (num.charAt(i - 1) == 'c' || num.charAt(i - 1) == 'C')
a = 12;

else if (num.charAt(i - 1) == 'd' || num.charAt(i - 1) == 'D')
a = 13;

else if (num.charAt(i - 1) == 'e' || num.charAt(i - 1) == 'E')
a = 14;

else if (num.charAt(i - 1) == 'f' || num.charAt(i - 1) == 'F')
a = 15;

else
a = Character.getNumericValue(num.charAt(i - 1));
prod = prod + (a * Math.pow(16, ctr));
ctr++;
}
return (int) prod;
}

public static void main(String[] args) {
int num;
String numS;
num = 123;