Created
October 26, 2015 22:27
-
-
Save akhenakh/7d070a82d0c3a69a48b8 to your computer and use it in GitHub Desktop.
Calculate checksum for an xbee frame on iOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void checksum(uint8_t *buf, int length, uint8_t *dstbuf, int *retlength) { | |
uint16_t sum = 0; | |
// then calculate checksum | |
for (int i=3;i<length-1;i++) { | |
sum+= buf[i]; | |
} | |
sum = CFSwapInt16HostToBig(sum); | |
uint8_t right = (sum >> 8) & 0xff; | |
uint8_t checksum = 0xFF - right; | |
buf[length -1] = checksum; | |
// We escape everything but the 1st 0x7D | |
// START_BYTE (0x7e), ESCAPE (0x7d), XON (0x11) and XOFF (0x13) | |
NSUInteger pos = 1; | |
uint8_t *ptrb = buf; | |
// skip 1st char | |
ptrb++; | |
dstbuf[0] = XBEE_START_MARK; | |
for (int i=1;i<length;i++) { | |
// escape if needed (api mode 2) | |
// ESCAPE (0x7d) | |
if (*ptrb == XBEE_START_MARK || *ptrb == 0x7d|| *ptrb == 0x11 || *ptrb == 0x13) { | |
dstbuf[pos] = 0x7d; | |
pos++; | |
dstbuf[pos] = *ptrb ^ 0x20; | |
} else { | |
dstbuf[pos] = *ptrb; | |
} | |
pos++; | |
ptrb++; | |
} | |
*retlength = pos; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment