将包含“0x00”的字节数组替换为“0x30”

时间:2014-05-08 14:02:44

标签: java android byte bytearray android-bluetooth

我正在尝试将包含0x00的字节数组替换为0x30

1) 如果字节数组是string形式。 (DO-能)

 String bytes = "0x7d 0x44 0x14 0x05 0x0e 0x01 0x11 0x04 0x2b 0x0c 0x00 0x45";

 if(bytes.contains("0x00"))
    bytes = bytes.replace("0x00", "0x30");

2) 如果字节数组是byte形式。 (有问题)

byte[] bytes = new byte[] { (byte) 0x7d,  (byte) 0x44,  
               (byte)0x2d,  (byte)0x05,  (byte) 0x0e,  (byte)0x01,  
               (byte)0x11,  (byte)0x10,  (byte)0x2f,  (byte) 0x03,  
               (byte)0x00,  (byte)0x48};

try 
{
    String myString = new String(bytes, "US-ASCII").trim();

    if(myString.contains("0x00"))
    {
        myString = myString.replace("0x00", "0x30");
        bytes = myString.getBytes();
    }
} 
catch (UnsupportedEncodingException e) 
{
    e.printStackTrace();
}

上述方法需要先将字节转换为字符串形式,然后用0x00替换所有0x30的出现,然后将结果字符串转换回字节。 这似乎不符合标准。然而,尽管解决方案没有奏效。

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解你的问题,但这应该会修复你的第二个清单:

byte[] bytes = new byte[] { (byte) 0x7d,  (byte) 0x44,  
               (byte)0x2d,  (byte)0x05,  (byte) 0x0e,  (byte)0x01,  
               (byte)0x11,  (byte)0x10,  (byte)0x2f,  (byte) 0x03,  
               (byte)0x00,  (byte)0x48};


for (int i=0; i<bytes.length; i++) {
    Byte b = bytes[i];
    if (b == 0x00) bytes[i] = 0x30;
}

try 
{
    String myString = new String(bytes, "US-ASCII").trim();
} 
catch (UnsupportedEncodingException e) 
{
    e.printStackTrace();
}