tags:

views:

5780

answers:

3

Hi, I'm begginer in java I'm reading data from serial port and I have stored the data in string array data is 24 byte length.

Data I'm getting as output: 12120814330006050.0

data also contains hexadecimal character in the string I want to read first character of the string. I have done:

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

But I'm getting NumberFormatException.plz help me to read hexadecimal character.

Thanks for reply

+1  A: 

hi

single characters you can get from a string with

str.getChar(0);

When you know that the string contains hex values in every character you dont have to convert every single character. You can put the complete string in and get the dec value of the hex string back. Otherwise you only calculate 1 hex value and has to multiplicate with the index number of the character position.

To parse it to an hex value you can call

Integer.parseInt(str,16);
Markus Lausberg
A: 

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

So:

  1. Check the contents of the string.
  2. Check the contents of the substring.
Douglas Leeder
A: 

It sounds like your data stream actually contains a mixture of binary and text data. It's very important (IMO) that you don't try to store the whole thing as a string. Keep it as binary data, and convert appropriate chunks into text when you need to.

This may mean changing how you're reading from the serial port in the first place - use APIs which deal in bytes and byte arrays instead of chars and strings.

Jon Skeet