How to Convert Decimal to Hexadecimal in Java
How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10 to 15 are represented by alphabets from A to F. There are two methods to convert Hexadecimal to decimal are as follows:
- Using toHexString() method
- Using user-defined logic
public class DecimalToHexaExample { public static void main(String args[]) { String str1=Integer.toHexString(34); String str2=Integer.toHexString(75); System.out.println(str1); System.out.println(str2); } }Output
22 4bUsing user-defined logic You can convert decimal to hexadecimal in using user-defined logic. Example In the following example, we have taken two variablesdecnum (represent decimal number) and rem (represent remainder). We have initialized 45 todecnum. A String type variable hexdecnum initialized to null and it stores the convertedhexadecimal value.We have defined an array hex[]of type charand initialized hexadecimal valuesfrom 0 to F to it. The while loop has the condition decnnum>0 which will repeatedly perform the operations in the while block until decnumis greater than 0 otherwise terminate the execution.The body of the while loop contains three statements. The first statement finds the remainder on dividing decnum by 16, which is obtained by using a modulo operator. In the second statement, the hex[rem] converts the remainder (rem) into character equivalent and concatenates theremainder(rem) into hexdecnum,and stores the results into the variable hexdecnum. The third statement updates the value ofdecnum, i.e., it divides the value by 16 and takes the quotient. These steps perform the operation in the while block until the conditiondecnum>0 becomes false. When the execution of the while loop is completed the println statement prints the hexadecimalrepresentation of the variable decnum which is stores in hexdecnum. It prints the array in reverse order. Remember:If you write the second statement of while loop like this: hexdecnum=hex[rem]+hexdecnum then the output will be 2D.When you change the sequence of the seconds tatement i.e. hexdecnum=hexdecnum+hex[rem]then the hexadecimal representation of 45 will be D2 which is the wrong output.So remember the sequence while you write this statement. This statement performs concatenation instead of addition. One more thing to remember, if you assign any digitamong0 to 9it gives the same digit as output but in string form.
public class DecimalToHexaExample1 { public static void main(String args[]) { intdecnum=45, rem; String hexdecnum=""; char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; while(decnum>0) { rem = decnum%16; hexdecnum = hex[rem] + hexdecnum; decnum = decnum/16; } System.out.println("Hexadecimal Value of 45 is:"+hexdecnum); } }Output
Equivalent Hexadecimal Value of 0 is: 2D