2014-08-28 47 views
1

我一直在使用PL2303電纜,並試圖從字符串這種方法如何將字節轉換爲Android USB Host中的字符串?

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); 

轉換連接,但沒有任何幫助。請回復我。

來源: Method Link

Target Method[updateReceivedData(byte[] data)]

Project Link

Screenshot Link

+0

你有方法** System.Text.Encoding.UTF8.GetChars(字節[]消息)**可用?另外,數據是否以十進制(或十六進制數據)的形式顯示? – jbutler483 2014-08-28 12:37:19

+0

@ jbutler483不,它在字節[]中。 – Pandian 2014-09-02 09:23:13

+0

將**字節[]消息**從上面更改爲您的**字節[]數組的名稱** – jbutler483 2014-09-02 09:29:15

回答

1
我目前使用的字符串和字節[](反之亦然)之間UTF8編碼

這樣做[在c#,但你應該得到大致的想法:)]使用;

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; 
} 

可能有點混亂,但你應該能夠明白。

EDIT

在java中;解碼字節數組應該類似於:

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

或者喜歡的東西:

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(); 
    } 
} 
+0

不要運氣兄弟....我得到同樣的東西。 。輸出是:^g 。 – Pandian 2014-09-02 10:41:25

+0

看起來像你使用錯誤的波特率(默認是9600)? – jbutler483 2014-09-02 10:43:29

+0

我試過了一切,這些都沒有奏效。 – Pandian 2014-09-02 16:33:22

1

先不要硬編碼字符集

如果你想將字符串轉換爲二進制數組,那就是pecial class從Apache開源的知道Base64 。

將以下jar添加到您的庫中。 公地編解碼器1.2.jar

試試這個:

byte[] decodeByteArray = Base64.decodeBase64(data); //data is Source Byte Array from updateReceivedData method 
String dataString = new String(decodeByteArray); 
相關問題