javacharintrxtx

Difference between char (int) and int


I have a piece of code, that receives values from a sensor (Via serialport using rxtx) and displays it. Strangely, the following code

int value = in.read();
System.out.print((char) value);

Outputs the desired value as:

RXTX Warning:  Removing stale lock file. /var/lock/LK.005.018.009
20
27
29
26
21

But when I change the above code as following:

int value = in.read();
System.out.print("The value is"+(char) value);

The output becomes:

RXTX Warning:  Removing stale lock file. /var/lock/LK.005.018.009
The value is2The value is6The value is
The value is2The value is2The value is

As it can be seen, the integer splits. For quite a while, I am unable to figure it out?

Is there a way where I can save the console value into an integer, as I would be using this value in the future.


Solution

  • As it can be seen, the integer splits. For quite a while, I am unable to figure it out?

    You are not reading integers, you are reading bytes which have characters encoded as ?ASCII?

    Is there a way where I can save the console value into an integer, as I would be using this value in the future?

    The simplest way is to use a Scanner

    Scanner scanner = new Scanner(in);
    while (scanner.hasNextInt()) {
       // read bytes up the next whitespace, parse as a int
       int n = scanner.nextInt();