I am communicating with a device via serial in Android. The result I am getting is:
01H 50H 30H 02H 28H 34H 45H 38H 39H 42H 42H 41H 43H 29H 03H 48H
where last hex code ie: 48H is Block Check Character(BCC).
And as per document it says that BCC is checksum byte from the second byte to the byte of the last but one.
I tired following method to get the BCC but it gives me 38H which does not matches with the device output.
byte[] inputByteArray = {0x50,0x30,0x02,0x28,0x34,0x45,0x38,0x39,0x42,0x42,0x41,0x43,0x29,0x03};
int sum = 0;
for (byte b : inputByteArray) {
sum = (sum + b) & 0xFF;
}
int compliment = (sum ^ 0xFF);
int adding1 = compliment + 1;
sum = (((sum ^ 0xFF) + 1) & 0xFF);
I am not able to figure it out that how it is calculated from the given hex output from the device. I need to find the logic since, the same way I need to calculate the other BCC values for my next request.
Any kind of help will really be appreciated.
First get the sum of all byte in the array
byte[] inputByteArray =
{0x50,0x30,0x02,0x28,0x34,0x45,0x38,0x39,0x42,0x42,0x41,0x43,0x29,0x03};
int sumByte = 0;
for (int x = 1; x < inputByteArray .length; x++) {
sumByte += inputByteArray [x];
}
//sumByte = 712
A method to calculate BCC
public int getBCCbyte(int sumByte){
double BCCInDouble = 0;
int ToFindBCC = sumByte;
//Get the Binary String of the SUM
String binary = Integer.toBinaryString(ToFindBCC);//(1011001000)
String finalBinaryBCC = binary.substring(binary.length() - 7);//(1001000)
//Convert the binary String to char array and calculate the decimal value
char[] binaryList = finalBinaryBCC.toCharArray();//[1,0,0,1,0,0,0]
for (int k = 0; k <= 6; k++) {
if (binaryList[k] == '1') {
BCCInDouble += Math.pow(2, 6 - k);
}
}
return (int) BCCInDouble;//72
}
Here 72 is the decimal value for 48H.
Hope this will be helpful for others.