1

I am trying to send data over bluetooth spp from an Android app. The code below takes a string, which works perfectly. Whatever I put in I get on hyperterminal at the other end of the connection.

   public void write(String message) {
        byte[] msgBuffer = message.getBytes();
        try {
            mmOutStream.write(msgBuffer);
        } catch (IOException e) {
            Log.d(TAG, "Error data send");     
          }
    }

However, I want to be able to send a hex value such as 0x41 for an 'A' in ASCII. How would I go about implementing this so that I could convert a string of say "41 7E" to the values 0x41 and 0x7E and then send them as is, so that on hyperterminal they come up as "A~"? I have tried using an example below but no success.

            public void writeHex(String str){
        char[] buffer = str.toCharArray();
        byte[] b = new byte[buffer.length];
        for  (int k=0; k < b.length; k++)
        {
            b[k] = (byte) buffer[k];

        try{
            mmOutStream.write(b);

        }catch (IOException e){
            Log.d(TAG, "Error data send");   
        }
        }
    }    

The values to be sent are read in from and editText when a button 'send' with an onClickListener is triggered. I have already formatted the editText so that only characters 0-9 and A-F are valid.

        hexSend.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    String hex = hexInput.getText().toString();
    mConnectedThread.writeHex(hex);
      Toast.makeText(getBaseContext(), "Hex Data Sent", Toast.LENGTH_SHORT).show();
    }
  });    
Harg
  • 365
  • 2
  • 18
  • 1 ascii = 1 byte. So the writing logic should have no problem. Could you post how you are reading them? – robermann Apr 04 '14 at 09:21
  • but your input string does contain either "A~" or "41 7E"? – robermann Apr 04 '14 at 09:31
  • An A in ASCII = 0x41. So i would like to be able to use the method like this, writeHex("41") and on the otherside of the Bluetooth connection in hyperterminal get 'A'. For some reason I get 441 come up in hyperterminal – Harg Apr 04 '14 at 09:56
  • Added how I read in the value in the main question window. – Harg Apr 04 '14 at 15:37
  • why don't you write on the server side the plain string? it would be easier, and you'd change just the client logic. on this i'll give a try – robermann Apr 04 '14 at 15:51
  • no work required, already done: http://stackoverflow.com/questions/923863/converting-a-string-to-hexadecimal-in-java – robermann Apr 04 '14 at 15:55

0 Answers0