For strings that may have "0x"
prefix, call Integer.decode(String). You can use it with Scanner,
try (Scanner s = new Scanner("0x11 0x22 0x33")) {
while (s.hasNext()) {
int num = Integer.decode(s.next());
System.out.println(num);
}
}
catch (Exception ex) {
System.out.println(ex);
}
Unfortunately, unless the input is very short, Scanner is ridiculously slow. Here is an efficient hand-made parser for hexadecimal strings:
static boolean readArray(InputStream stream, int[] array) {
int i = 0;
final int SPACE = 0;
final int X = 1;
final int HEXNUM = 2;
final int ERROR = -1;
for (int next_char= -1, expected = SPACE; i <= array.length && stream.available() > 0 && expected != ERROR; next_char = stream.read()) {
switch (expected) {
case SPACE:
if (Character.isWhitespace(next_char))
;
else if (next_char == '0') {
array[i] = 0;
expected = X;
}
else {
LOGGER.e("unexpected '" + next_char + "' for " + expected + " at " + i);
expected = ERROR;
}
break;
case X:
if (next_char == 'x' || next_char == 'X') {
expected = HEXNUM;
}
else {
LOGGER.e("unexpected '" + next_char + "' for " + expected + " at " + i);
expected = ERROR;
}
break;
case HEXNUM:
if (Character.isDigit(next_char)) {
array[i] *= 16;
array[i] += next_char - '0';
}
else if (next_char >= 'a' && next_char <= 'f') {
array[i] *= 16;
array[i] += next_char - 'a' + 10;
}
else if (next_char >= 'A' && next_char <= 'F') {
array[i] *= 16;
array[i] += next_char - 'A' + 10;
}
else if (Character.isWhitespace(next_char)) {
i++;
expected = SPACE;
}
else {
LOGGER.e("unexpected '" + next_char + "' for " + expected + " at " + i);
expected = ERROR;
}
}
}
}
if (expected == ERROR || i != array.length) {
LOGGER.w("read " + i + " hexa integers when " + array.length + " were expected");
return false;
}
return true;