Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read/write raw hex bytes from input/output stream in BluetoothChat?

I'm developing an app based on the BluetoothChat sample code. I need to be able to write a byte array containing hex values to the output stream. I also need to parse through the byte array on the inputstream and read the hex values. Here's my code just to simply write hex values to the byte array

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

However, when stepping through debug and watching "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 is happening when I watch byte[] buffer when reading the inputstream.

 // Read from the InputStream
 bytes = mmInStream.read(buffer);

I sent a byte array containing hex values, but byte[] buffer is showing ascii values. How can I read and write the raw hex values over bluetooth? Some of the read/write streams will be short <15byte stream for commands. But I'll also need to read a large file encoded as hex bytes. Any suggestions for that input stream? Do I need to use BufferedInputStream?

like image 463
jawin Avatar asked Nov 08 '12 21:11

jawin


1 Answers

When you write

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

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

Now we might wonder how does this conversion occur. By default, the int value is converted to its decimal representation. This is what most humans are used to reading and expect to see. As programmers, we sometimes need to think of the hexadecimal representation of an int value, such as you are doing in your code. However, the computer does not automatically know this just because we set the value of a variable using a hexadecimal representation. In particular, your IDE still defaults to displaying all int data in its decimal representation.

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

like image 166
Code-Apprentice Avatar answered Nov 14 '22 21:11

Code-Apprentice