0

I've found method toHexString() but it converts string into hex, while the value is already converted (like "20 0F 01 etc."). What's the best way to get hex values from this String for later purposes (ex. adding, sending some of them to output device)?

gooornik07
  • 99
  • 12
  • 2
    You want to parse hex string into `int`? If so `Integer` have method `parseInt` with two parameters, last one is radix, pass 16 there. – talex Nov 02 '16 at 16:00
  • Actually it would be better to be able to have it in byte array like: byte[] {0x20, 0x20, 0x0F, 0xFF} – gooornik07 Nov 02 '16 at 16:06
  • 1
    Then split string by `yourString.split(" ")` before parsing. – talex Nov 02 '16 at 16:07
  • Possible duplicate of [Convert a string representation of a hex dump to a byte array using Java?](http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java) – Oleg Estekhin Nov 02 '16 at 16:14

3 Answers3

0

Try

Integer.parseInt(String val, int radix)

Example Integer.parseInt("-FF", 16) returns -255

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int)

Massimo Petrus
  • 1,881
  • 2
  • 13
  • 26
0

Use String.split() to break the string up into individual bytes, and Integer.parseInt(s, 16) to convert the string representation into an integer.

Something like this should work:

List<Integer> parseHex(String hex) {
    ArrayList<Integer> a = new ArrayList<Integer>();
    for (String s : hex.split("\\s+")) {
          a.add(Integer.parseInt(s, 16));
    }
    return a;
}
Mike Harris
  • 1,487
  • 13
  • 20
0

Since you mention preferring a byte array, you can use a ByteBuffer to accumulate byte values:

String text = "20 0F 01";

ByteBuffer buffer = ByteBuffer.allocate((text.length() + 1) / 3);
Scanner scanner = new Scanner(text);
while (scanner.hasNextInt(16)) {
    buffer.put((byte) scanner.nextInt(16));
}

byte[] bytes = buffer.array();

We use hasNextInt and nextInt, rather than hasNextByte and nextByte, because Java’s numeric types are signed, and values above 7f are not representable as signed bytes.

VGR
  • 40,506
  • 4
  • 48
  • 63