2011-08-05 76 views
4

我有一個字符串,我有與字節數組來連接,所以我嘗試這個字符串和字節數組級聯

String msg = "msg to show"; 

byte[] msgByte = new byte[msg.length()]; 

try { 
msgByte = msg.getBytes("UTF-8"); 
} catch (UnsupportedEncodingException e) { 
e.printStackTrace(); 
} 

byte[] command = {2,5,1,5} 

byte[] c = new byte[msgByte.length + command.length]; 
System.arraycopy(command, 0, c, 0, command.length); 
System.arraycopy(msjByte, 0, c, command.length, msjByte.length); 

for(Byte bt:c) 
    System.out.println(bt+""); 

這是輸出:
2 5 1 5 109 115 103 32 ... ...

但是我正在尋找的結果是這樣的
2 5 1 5味精...

我需要在一個陣列中的原因,而是作爲一個藍牙打印機的命令。

有沒有辦法,有什麼建議?

在此先感謝! :)

+0

你有正確的結果。 ascii(109)= m。這是一個相當低級別的界面,混合命令代碼和字符串? –

+0

我的錯誤,我以爲我錯過了數組中的ASCII碼,因爲打印機的示例命令來這樣的事情:byte [] ESC_Z2 = {0x1b,0x5a,0x00,0x51,0x05,0x14,0x00, '信息' };所以我試着發送純粹的ASCII代碼,但它不起作用,但它是由於命令 –

回答

3

您不能有一個包含'2 5 1 5 m s g'的字節數組。來自documentation

字節數據類型是一個8位有符號二進制補碼整數。它有 最小值-128和最大值127(含)。

我不能設想一個場景,你實際上想用字符串連接未編碼的字節,但是這裏有一個解決方案返回char[]

public static void main(String[] args) { 
    final String msg = "msg to show"; 
    final byte[] command = { 2, 5, 1, 5 }; 

    // Prints [2, 5, 1, 5, m, s, g, , t, o, , s, h, o, w] 
    System.out.println(Arrays.toString(concat(msg, command))); 
} 

private static char[] concat(final byte[] bytes, final String str) { 
    final StringBuilder sb = new StringBuilder(); 
    for (byte b : bytes) { 
     sb.append(b); 
    } 
    sb.append(str); 
    return sb.toString().toCharArray(); 
} 
1

另一種方法是做到這一點...

String msg = "msg to show"; 
char[] letters = msg.toCharArray(); 
byte[] command = {2,5,1,5}; 
String result; 
for (String str: command) { 
    result += str + " "; 
} 
for (String str: letters) { 
    result += str + " "; 
} 
System.out.println(result); 
+1

上的參數,你可以有字節的字節,你只需要知道你在做什麼。只要你對編碼清楚,將字符<127作爲字節呈現就沒有問題。 –

+0

謝謝你接受!我會改變我的答案。 – fireshadow52

+0

@Jochen:我不同意。該選舉委員會明確指出,他正在尋找的結果是'2 5 1 5 m s g'。一個字節數組只能包含整數。我知道你的意思,但是OP對這些角色的「編碼」並不滿意,因爲他已經試過了(2 5 1 5 109 115 103 32)。 – hoipolloi