1

I have the following problem: I am sending an array to serial port it looks like this

 byte arr[] = new byte[]{0x18, 0x1B, 0x02, 0x05, 0xFF, 0x01, 0x10,
                         0x21,0x30, 0x00, 0x00, 0x6A, 0x28, 0x1B,0x03}

Here comes the problem - I have 3 text fields with R , G , B colors . I get the values from them as String.But I cant convert them to the above format 0xHexValue and put them in the byte array. I've tried a lot of approaches but without any success.

EDIT : I get the values from the text fields of the GUI with txtField.getText() after that there is no problem to convert in example R 200 , G 0 , B 0 to HEX C8 00 00 but I cant insert HEX into my byte array because it's still string . When i try to convert strings to byte with Byte.parseByte(s) some negative values appear....

EDIT 2 Byte.valueOf(myString) gets an exception on value 200

java.lang.NumberFormatException: Value out of range. Value:"200" Radix:10

GUYS: I see your posts and I suggest to focus on this : How to make in example this String "C8" to fit in the arr[] with the proper format 0xC8 and of course as byte not as String...

cyrat
  • 628
  • 1
  • 11
  • 20

2 Answers2

2

Use Byte.parseByte

Byte.parseByte(inputString,16);

16 is hexadecimal radix


You can also use Byte.decode

Byte.decode(inputString);//inputString can be decimal, hexadecimal, and octal numbers
Anirudha
  • 32,393
  • 7
  • 68
  • 89
1

Try this:

    List<Byte> byteList = new ArrayList<>();
    String data = "0x18, 0x1B, 0x02, 0x05, 0xFF, 0x01, 0x10,0x21,0x30, 0x00, 0x00, 0x6A, 0x28, 0x1B,0x03";
    Pattern hexPattern = Pattern.compile("0x(..)");
    Matcher matcher = hexPattern.matcher(data);

    while(matcher.find()) {
        byteList.add((byte)Integer.parseInt(matcher.group(1), 16));
    }

    System.out.println(">>> " + byteList);

You can change the byteList by an actual byte array. Also, I'm assuming that you have your String in a certain way, but the idea is this one.

morgano
  • 17,210
  • 10
  • 45
  • 56