I am trying to replace byte array occurrence that contains 0x00 to the 0x30.

1) If byte array is in string form. (Do-able)

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

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

2) If byte array is in byte form. (Problematic)

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();
}

The above method requires to first convert bytes into string form and then replace all the occurences of 0x00 with 0x30 and then convert the resultant string back to bytes. This seems something not upto the mark. However, despite of that the solution didn't worked.

有帮助吗?

解决方案

I am not sure whether I undestand your question, but this should fix your second listing:

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();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top