Reputation: 4455
I would like to convert a string with the form "AA BB CC" or "0xAA 0xBB 0xCC" to an array of bytes. Reading the documentation of Scanner
looked promising.
I assumed that hasNextByte()
and getNextByte()
would do the job but in fact not byte seems to be detected. The code is pretty simple:
byte[] bytesFromString(String value) {
List<Byte> list = new ArrayList<>();
Scanner scan = new Scanner(value);
while(scan.hasNextByte(16)) {
list.add(scan.nextByte(16));
}
byte[] bytes = new byte[list.size()];
for(int i = 0; i < list.size(); i++){
bytes[i] = list.get(i);
}
return bytes;
}
I always receive an empty array as output: hasNextByte(16)
never detects the byte.
Any particular reason why it is not working?
Upvotes: 0
Views: 193
Reputation: 33875
The problem is that your values (AA
BB
and CC
) are out of range for byte
, since byte
is signed.
A possible workaround is to read the values as short
and then cast to byte
:
while (scan.hasNextShort(16)) {
list.add((byte) scan.nextShort(16));
}
Printing the results, you will see that the values are negative:
String input = "AA BB CC";
byte[] result = bytesFromString(input);
System.out.println(Arrays.toString(result)); // [-86, -69, -52]
Showing the overflow.
Upvotes: 1