Java – how do I read / write raw hexadecimal bytes from I / O streams in Bluetooth chat?
I am developing an application based on Bluetooth chat sample code I need to be able to write a byte array containing hexadecimal values to the output stream I also need to parse the byte array on the input stream and read the hexadecimal value This is my code, which simply writes hexadecimal values to a byte array
byte[] data = new byte [3]; data[0] = (byte) 0x53; data[1] = (byte) 0x1C; data[2] = (byte) 0X06;
However, when stepping through debugging and observing "data", the debugger will display the values as data [0] = 83, data [1] = 28, data [2] = 6 Why are all values converted to ASCII? The same thing happens when I look at the byte [] buffer while reading the input stream
// Read from the InputStream bytes = mmInStream.read(buffer);
I sent a byte array containing hexadecimal values, but the byte [] buffer shows the ASCII value How do I read and write original hexadecimal values via Bluetooth? For commands, some read / write streams will be short < 15 byte streams But I also need to read a large file encoded in hexadecimal bytes Any suggestions for this input stream? Do I need to use bufferedinputstream?
Solution
When you write
int answer = 42; System.out.println(answer);
The int value stored in the answer variable is converted to string and displayed on the monitor The same applies to displaying values in the debugger of the IDE Eventually, all numeric data will be converted to ASCII (or some other character encoding) to display it This is true in any programming language
Now we may want to know how this transformation occurs By default, int values are converted to their decimal representation This is what most people are used to reading and expect to see As programmers, we sometimes need to consider the hexadecimal representation of int values, such as what you do in code However, the computer will not automatically know this because we use hexadecimal representation to set the value of the variable In particular, the IDE still displays all int data in decimal representation by default
Fortunately, IDE designers are programmers and realize that we sometimes need to view int data in different forms You can change the debugger settings to display data in hexadecimal Since the steps to do this depend on your IDE, you should check the help file for details