Context: Java 22
I'm trying to read data from a table that includes both Hex and Dec values in a CSV. These values would look something like this:
0x00000000,0
0x03000000,1
0x05000000,2
What I'm having trouble doing is pulling the hex values (0x... included) and assigning them to an int variable.
The declaration int num = 0x05000000;
works but when I try to pull these values from the Scanner, I hit a wall.
I need the int variable to include the 0x
prefix as I'm using them in to assign color data, which needs the 0x when working with an Alpha channel.
I've gotten to the point where I can pull the Dec value from the table (in either Int or Long form), but don't know how to convert it back to the 0x........
form, while remaining in a numerical data type.
Here's where I've landed so far.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner("0x000000, 0, 0x03000000, 1, 0x05000000, 2");
s.useDelimiter(", ");
while (s.hasNext()) {
try {
int num = Integer.decode(s.next());
System.out.println(num);
} catch (InputMismatchException e) {
System.out.println("Input Mismatch");
s.skip(", ");
}
}
}
}
Output
0
0
50331648
1
83886080
2
All of these are Decimal integers. I need them to remain in their "0x..." state as hex integers.
Ideally I'd like an output that reads closer to
0x00000000 (Hex int)
0 (Dec int)
0x03000000 (Hex int)
1 (Dec int)
0x05000000 (Hex int)
2 (Dec int)
I can use any numerical datatype (long, float, double, etc), but I'm having trouble returning the specific hex codes as numerical data.
I don't know how to convert it back to the 0x........ form, while remaining in a numerical data type.
This is not possible. An int
is just a number, it isn't hex or decimal. Only when you display it as a String
is it hex or decimal.
If you want to keep it as hex or decimal, you must keep it as a String
, not an int
.
You can alternately print a number in hexadecimal, with e.g. Integer.toHexString(int)
, but you will have to know which numbers to display in hexadecimal and which not.