Certainly! I can provide you with an example code snippet in Java that converts a hexadecimal number to its decimal equivalent.
Here's an implementation using the built-in functions:
public class HexToDecimalConverter {
public static int hexToDecimal(String hexNumber) {
// Remove any leading "0x" if present
if (hexNumber.startsWith("0x")) {
hexNumber = hexNumber.substring(2);
}
// Convert the hexadecimal string to decimal
int decimalNumber = Integer.parseInt(hexNumber, 16);
return decimalNumber;
}
public static void main(String[] args) {
String hexNumber = "1A";
int decimalNumber = hexToDecimal(hexNumber);
System.out.println("Hexadecimal: " + hexNumber);
System.out.println("Decimal: " + decimalNumber);
}
}
In this code, we define a class called HexToDecimalConverter with a hexToDecimal method that takes a hexadecimal number as input and returns its decimal equivalent. The main method demonstrates the usage of the hexToDecimal method by converting the hexadecimal number "1A" to decimal and printing the result.
The hexToDecimal method first checks if the input string starts with "0x" (as some hexadecimal representations may include this prefix). If it does, the prefix is removed using the substring method.
Then, the method uses the parseInt method from the Integer class to parse the hexadecimal string and convert it to decimal. The second argument, 16, specifies that the input string is in base 16 (hexadecimal).
Finally, the decimal value is returned, and the result is printed in the main method.
When you run this code, the output will be:
Hexadecimal: 1A
Decimal: 26
So, the hexadecimal number "1A" is converted to its decimal equivalent, which is 26.