我有一个字符串,我必须与字节数组连接,所以我尝试了这个
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 msg ...
我需要它在一个阵列中,因为它被用作蓝牙打印机的命令。
有没有办法,有什么建议吗?
提前致谢! :)
I have a String that I have to concatenate with an byte array, so I tried this
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+"");This is the output: 2 5 1 5 109 115 103 32 ... but the result that I'm looking for is this 2 5 1 5 m s g ...
I need it in one array cause it's used as a command for a bluetooth printer.
Is there a way, any suggestions?
Thanks in advance! :)
最满意答案
你不能有一个包含'2 5 1 5 ms g'的字节数组。 从文档 :
字节数据类型是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(); }You can't have a byte array containing '2 5 1 5 m s g'. From the documentation:
The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
I can't envisage a scenario where you would actually want to join un-encoded bytes with a string, but here's a solution that returns a 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(); }更多推荐
发布评论