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...

5
  • How are the values stored in the string? "0x18", "18", ...? Commented Jul 23, 2013 at 12:06
  • Can you please show us how you tried it? Commented Jul 23, 2013 at 12:08
  • Byte.parseByte(string,radix); Commented Jul 23, 2013 at 12:08
  • (Note that you'd need to somehow strip off the "0x" first, before using parseByte.) Commented Jul 23, 2013 at 12:11
  • Possibly see this, this. Commented Jul 23, 2013 at 12:12

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

What do you assume the input to be in OP's case ?
Please mention what sort of String i.e. contents of the string.
@TheNewIdiot it could be anything "0x", "0X", "#", or leading zero
Not for me , please add it to the answer.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.