简体   繁体   中英

Convert ascii to int Value

I receive through the serial an ascii value used to display the rpm value of an encoder, I am trying to convert these values to an int but I am having a problem with some values, the following error returns me sometimes java.lang.NumberFormatException: Invalid int: "2"

 public void run() {
                    byte[] rpm =  (read.getBytes(StandardCharsets.US_ASCII));


                    if(rpm.length >=12) {


                       char ch0 = (char) rpm[9];
                        char ch1 = (char) rpm[10];


                        String s = new StringBuilder().append(ch0).append(ch1).toString();

                         a = Integer.parseInt(s,16);

the log for values ch0 and ch1

在此处输入图像描述

The error 'invalid int: "2"' cannot occur here. It's actually invalid int: "X2X", where one of the Xs is some space-looking character, probably an actual space (ascii 0x20), possibly a null character (ascii 0x00).

You'd need to read the docs of the protocol. evidently it sometimes sends 0x30 0x44 (which is ascii-ese for "0D"), which is to be parsed as a hex string and meaning: the decimal value of 13. But sometimes it sends, for example, 0x20 0x32 (ascii-ese for a space followed by the digit 2), which you can't pass to parseInt like this, you'd have to get rid of that space.

Your edits and comments don't actually make clear what you get; print the raw value of rpm[9] and rpm[10] to know.

Another option is that you've desynced: The protocol for example says that the 'next 4 bytes are the length' and you only read 3, so now you're off-by 1, and you're reading a space-like character which is not part of the hex digit but the earlier stuff, and the first of the 2 hex digits (2), and then tossing that at parseInt. I say that, because a protocol that sometimes sends "0D" and sometimes sends " 2" (that's a space, then a 2), is bizarre. It feels like the more logical explanation is that your code has a bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM