I found an exercise to convert from hex to decimal using casting, but I did not understand how that decimal + 'A' - 10
worked. Can anybody explain me?
code is here:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a decimal value (0-15):");
int decimal = input.nextInt();
if (decimal <= 9 && decimal >= 0) {
System.out.println("The hex value is: " + decimal);
}
else if (decimal >= 10 && decimal <= 15) {
System.out.println("The hex value is " + (char)(decimal + 'A' - 10));
}
else {
System.out.println("It's an invalid input.");
}
}
}
Thanks.
Each char has integer value associated with it. Hence casting int to (char) will yield to char value.
The alphabetical characters in Unicode have sequential codes:
A = 65 B = 66 C = 67 D = 68 ...
So, the value of (char)('A'+1)
is the same as 'B'
, as the char
value 'A'
is interpreted as 65 when used in an arithmetic expression, and then the +1 makes it 66, and then you cast it as char again, it's 'B'
.
So what you have there is the value of 'A'
plus the difference between the decimal
and 10 (which is 0 through 5). This will give you the values 'A' + 0
, 'A' + 1
, 'A' + 2
etc, which means 'A'
, 'B'
, 'C'
respectively when you calculate it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.