0

I have a txt file, which is a String of Hex bytes separated by commas, for example:

0x01,0x02,0x03,0x04,0xA1,

I want to easily split this string by commas, and then have each Hex cast to a byte, but the only way I can get this working seems like a ludicrous amount of extra work.

Essentially I'm splitting into a String array, then having to loop through the String array to cast each individual "String" to a byte array using BigInteger, then looping through that byte array to cast it to a single byte and then adding that to a different byte array. Oh, and I have to manually remove the 0x from each "String" too.

String Data = "0x01,0x02,0x03,0x04,0xA1,";
String[] DataSplit = Data.split(",");
int DataLength = DataSplit.length;
byte[] byteArray = new byte[DataLength];

for(int i = 0; i < DataLength; i++) {

    String dataSingle = DataSplit[i].charAt(2) + "" + DataSplit[i].charAt(3); // remove 0x

    byte[] bytes = new BigInteger((dataSingle), 16).toByteArray();
    byte singleByte = 0;
    for (byte aByte : bytes) {
        singleByte += (byte) aByte;
    }

    byteArray[i] = (byte) singleByte;

}

This code works, but it's a stupid amount of code for such a basic process. This is being done in Android Studio for an Android App, but it's all Java

1

1 Answer 1

3

The loop is wildly over-complicated:

for(int i = 0; i < DataLength; i++) {
  byteArray[i] = (byte) Integer.parseInt(DataSplit[i].substring(2), 16);
}

(You need to use Integer.parseInt instead of Byte.parseByte in order to handle bytes greater than 0x7f).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.