String.getBytes provides default encoded characters. This is not recommended, even if you want to encode the string as bytes (assuming you provided the required encoding)
In this pase, you want to parse your hex string in bytes. An easy way to do this is to use BigInteger.
String hex = "CAFEBABE"; byte[] bytes = new BigInteger(hex, 16).toByteArray(); if (bytes.length > 0 && bytes[0] == 0) bytes = Arrays.copyOfRange(bytes, 1, bytes.length); System.out.println(Arrays.toString(bytes));
prints
[-54, -2, -70, -66]
source share