To convert decimal number (base 10) to hexadecimal number (base 16) we can use the Integer.toHexString()
method. This method takes an integer as parameter and return a string that represent the number in hexadecimal.
To convert back the number from hexadecimal to decimal number we can use the Integer.parseInt()
method. This method takes two argument, the number to be converted, which is the string that represent a hexadecimal number. The second argument is the radix, we pass 16
which tell the method if the string is a hexadecimal number.
package org.kodejava.lang;
public class ToHexadecimalExample {
public static void main(String[] args) {
// Converting a decimal value to its hexadecimal representation
// can be done using Integer.toHexString() method.
System.out.println(Integer.toHexString(1976));
// On the other hand to convert hexadecimal string to decimal
// we can use Integer.parseInt(string, radix) method,
// where radix for hexadecimal is 16.
System.out.println(Integer.parseInt("7b8", 16));
}
}
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023