How do I read / write hex bytes from an I / O stream in BluetoothChat?

I am developing an application based on the example of the BluetoothChat code. I need to write a byte array containing hexadecimal values โ€‹โ€‹to the output stream. I also need to parse the byte array in the input stream and read the hexadecimal values. Here my code just simply writes the hexadecimal values โ€‹โ€‹to an array of bytes

byte[] data = new byte [3]; data[0] = (byte) 0x53; data[1] = (byte) 0x1C; data[2] = (byte) 0X06; 

However, when debugging and viewing "data", the debugger shows the values โ€‹โ€‹as data [0] = 83, data [1] = 28, data [2] = 6. Why are all the 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 an array of bytes containing hexadecimal values, but byte [] shows the ascii values. How can I read and write hexadecimal values โ€‹โ€‹over bluetooth? Some of the read / write streams will be short and 15 bit streams for commands. But I will also need to read a large file encoded as hexadecimal bytes. Any suggestions for this input stream? Do I need to use a BufferedInputStream?

+6
source share
1 answer

When you write

 int answer = 42; System.out.println(answer); 

The int value stored in the answer variable is converted to String and then displayed on your monitor. The same applies to displaying a value in your IDE debugger. In the end, all numeric data is converted to ASCII (or some other character encoding) to display it. This is true in any programming language.

Now we may wonder how this transformation happens. By default, int converted to decimal. This is what most people use to read and expect to see. As programmers, we sometimes need to think about the hexadecimal representation of the int value, for example, in your code. However, the computer does not automatically know about it just because we set the value of the variable using the hexadecimal representation. In particular, your IDE still displays all int data in decimal notation by default.

Fortunately, IDE designers are programmers and understand that sometimes we need to see int data in a different form. You can change the settings for your debugger to display int data as hexadecimal. Since the steps for this depend on your IDE, you should check the help files for details.

+8
source

All Articles