如何将字节转换为Android USB Host中的字符串?
我一直在使用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
。
这样做[在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();
}
}
不要运气兄弟....我得到同样的东西。 。输出是:^g 。 – Pandian 2014-09-02 10:41:25
看起来像你使用错误的波特率(默认是9600)? – jbutler483 2014-09-02 10:43:29
我试过了一切,这些都没有奏效。 – Pandian 2014-09-02 16:33:22
先不要硬编码字符集
如果你想将字符串转换为二进制数组,那就是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);
你有方法** System.Text.Encoding.UTF8.GetChars(字节[]消息)**可用?另外,数据是否以十进制(或十六进制数据)的形式显示? – jbutler483 2014-08-28 12:37:19
@ jbutler483不,它在字节[]中。 – Pandian 2014-09-02 09:23:13
将**字节[]消息**从上面更改为您的**字节[]数组的名称** – jbutler483 2014-09-02 09:29:15