将String(表示HEX)转换为字节数组的有效方法? Android的

时间:2014-08-25 08:15:48

标签: java android string byte bytearray

我正在开发一个涉及通过无线接收字节数组的项目,Android应用程序通过TCP连接将其读取为字符串:

input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
...
...
//Loop
String read = input.readLine();
//Do something meaningful with String read...

字符串将始终是固定格式,即前3个字符将是ID,接下来的20个字符将是消息数据。字符数量不会改变(3 + 20个字符= 23,起始和结束字符'['和']',因此总共有25个字符。

应用程序收到的字符串示例为[01A01020304050A0B0C0D]

  1. ID - 0x01A
  2. Byte0 0x01
  3. Byte1 0x02
  4. Byte2 0x03
  5. Byte3 0x04
  6. Byte4 0x05
  7. Byte5 0x0A
  8. Byte6 0x0B
  9. Byte7 0x0C
  10. 字节8 0x0D
  11. 我猜我必须使用子字符串操作,但我在将子字符串转换为字节值时遇到了问题(注意:应用程序期望byte []而不是字节[])我觉得我'我没有有效地做到这一点。我偶然发现了这段代码:

    public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
    

    这将返回一个大小为1的字节数组,并且每条消息必须运行9次(9字节)。我有点担心这在处理上可能有点过于费劲,特别是当应用程序非常频繁地接收消息时(大约每秒大约10-15条消息)

    我提前感谢任何想法和许多感谢!

5 个答案:

答案 0 :(得分:2)

只需使用:

byte[] decodedString = Base64.decode(your_string, Base64.DEFAULT);

答案 1 :(得分:0)

最简单的方法:

String myString = "This is my string";
byte[] myByteArray = myString.getBytes("UTF-8");

现在,您可以访问id,发送消息;很容易从myByteArray。

答案 2 :(得分:0)

byte[] b = string.getBytes();
byte[] b = string.getBytes(Charset.forName("UTF-8"));
byte[] b = string.getBytes("UTF-8");

没有办法比使用这种方法更有效率。

答案 3 :(得分:0)

只需写下您的数据

即可
  byte[] data = yourData.getBytes();
  os.write(data, 0, data.length) // data is of 23 bytes
  os.flush();

通过InputStream读取怎么样,正如你在问题中提到的那样,字符串是23个字符就像

  public byte[] readData(InputStream is) {
         byte[] data = new byte[23];
         int read = is.read(data);
         System.out.println("Read: " + read);
         return data;
 }

当您有数据时,您可以像这样分割数据

  byte[] tempId = new byte[3];
  System.arrayCopy(data, 0, id, 0, id.length);
  byte[] tempMessage = new byte[20];
  System.arrayCopy(data, 3, message, 0, message.length);

  String id = new String(tempId);
  String message = new String(tempMessage);

现在你将id和消息分开并转换为String。

答案 4 :(得分:-2)

byte[] array = String.getBytes("UTF-8");