Convert hex character string to integer in java

I am a beginner in java. I am reading data from a serial port and I have stored the data in 24 bytes long string data arrays.

The data I get as output is: 12120814330006050.0

the data also contains a hex character in the string that I want to read as the first character of the string. I did:

String str=dispArray[i].substring(1,2);
int i= Integer.parseInt(str,16);
System.out.println("Decimal:="+ i);

      

But I am getting NumberFormatException.plz to help me read the hex character.

thanks for the answer

0


source to share


3 answers


the individual characters you can get from the string with

str.getChar(0);

      

When you know that a string contains hexadecimal values โ€‹โ€‹in every character, you don't need to convert every character. You can put the whole string and get the dec value of the hex string. Otherwise, you only calculate one hex value and must multiply with the character position index number.



To parse it into a hexadecimal value, you can call

Integer.parseInt(str,16);

      

+3


source


It looks like your data stream actually contains a mixture of binary and text data. It is very important (IMO) that you are not trying to store the whole thing as a string. Store it as binary data and convert the corresponding chunks to text whenever you need.



This could mean changing the way you read from the serial port in the first place - using APIs that handle bytes and byte arrays instead of characters and strings.

+1


source


Java strings are unicode - so the bytes have already been decoded using some encoding (UTF-8 perhaps?).

So:

  • Check the content of the string.
  • Check the content of the substring.
0


source







All Articles