Question

I've got the following function to make a conversion from a Hex String to a Byte array. Then, I calculate the Checksum:

private String CalcChecksum (String message) {

    /**Get string's bytes*/
    //byte[] bytes = DatatypeConverter.parseHexBinary(message.replaceAll("\\s","")).getBytes();
    message = message.replaceAll("\\s","");
    byte[] bytes = hexToByteArray(message);
    byte b_checksum = 0;

    for (int byte_index = 0; byte_index < bytes.length; byte_index++) {
        b_checksum += bytes[byte_index];
    }

    int d_checksum = b_checksum;  //Convert byte to int(2 byte)
    int c2_checksum = 256 - d_checksum;  //Hacer complemento a 2
    String hexString = Integer.toHexString(c2_checksum);  //Convertir el entero (decimal) a hexadecimal

    return hexString;
}


public static byte[] hexToByteArray(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;
}

Making some test, for example for the hex value "e0", the hexToByteArray is getting the value "-32". So the final returning value in the CalcChecksum is "17a".

What I need is to get unsigned values in the hexToByteArray function. This is because i need to send the Checksum in a hexString to a MCU where the Checksum is calculated with unsigned values, so isntead of get the "-32" value, it gets "224" and the final hex value is "7a" instead of "17a".

i think that doing some kind of conversion like when the byte result is a negative value, do something like 255 + "negative value" + 1. This will convert "-32" into "224".

The problem is that i'm trying to do it, but i'm having some errors making the conversions between bytes, int, etc...

So, how could i do?

Was it helpful?

Solution

For the moment, I think that this can be the solution.

Just including in the CalcChecksum function the next code after int d_checksum = b_checksum;:

if (d_checksum < 0) {         
        d_checksum = 255 + d_checksum + 1;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top