1

I have connected using pl2303 cable and trying to convert string from this method

  private void updateReceivedData(byte[] data) {
      String tmpString=HexDump.dumpHexString(data);
      // I've Tried several methods like 
      String dataString=new String(data);
      String dataString=new String(data,""UTF-8"");
      String dataString=Byte.decode(tmpString);

but none has helped. Kindly reply me.

Source : Method Link

Target Method[updateReceivedData(byte[] data)]

Project Link

Screenshot Link

ekostadinov
  • 6,880
  • 3
  • 29
  • 47
Pandian
  • 474
  • 1
  • 4
  • 14

3 Answers3

1

I am currently using UTF8 encoding between string and byte[] (and vice versa).

This is done [in c#, but you should get the general idea :)] using;

using System.Text;    


public static String changeValue(byte[] msg)
{
String myMsg = "";
char[] msgAsChars = System.Text.Encoding.UTF8.GetChars(byte[] msg); 
//now should be a char array of your values

  for(int i=0;i<msgAsChars.Length;i++) 
  {
   //loop through your char array and add to string
    myMsg +=msgAsChars[i];
  }

return myMsg;
}

Might be a bit messy, but you should be able to get the idea.

EDIT

In java; decoding a byte array should be similar to:

String decoded = new String(bytes, "UTF-8");

Or something like:

to convert directly to String, you can always use

`String str = new String(byte[] byteArray);`

EDIT 2

public class Main {

    /*
     * This method converts a byte array to a String object.
     */

    public void convertByteArrayToString() {

        byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};

        String value = new String(byteArray);

        System.out.println(value);
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().convertByteArrayToString();
    }
}
jbutler483
  • 24,074
  • 9
  • 92
  • 145
1

First don't hard code your character Set

if your want to convert string to binary array, there is a special class know as Base64 from Apache Which is Open Source.

Add the following jar to your libs. commons-codec-1.2.jar

try this:

byte[] decodeByteArray  = Base64.decodeBase64(data); //data is Source Byte Array from updateReceivedData method
String dataString  = new String(decodeByteArray);
VegeOSplash
  • 214
  • 1
  • 3
0

Did you check your baud rate ? in sPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

I was using the wrong baud rate and i changed from 115200 to 9600, then, in the updateReceivedData method, i used, String s = new String(data);to convert the byte data into String.

Reejesh PK
  • 658
  • 1
  • 11
  • 27