Utility functions for working with data streams
Example usage:
http://andy.dynamicbits.com/hdradio/
#include "mbed.h" #include "checksum.h" DigitalOut myled(LED1); template <int T> struct data{ uint8_t buf[T]; uint8_t checksum; }; data<12> all_ones = {{1,1,1,1,1,1,1,1,1,1,1,1}}; int main() { calculateChecksum( all_ones.buf, sizeof(all_ones) ); for(int i=0; i<sizeof(all_ones); i++) { printf("%02d: %d\n", i, *(all_ones.buf+i)); } printf("checksum test: %s\n", (result)?"passed":"failed"); while(1) { myled = 1; wait(0.2); myled = 0; wait(0.2); } }
checksum.cpp
- Committer:
- sam_grove
- Date:
- 2013-03-07
- Revision:
- 1:ace4b3aef52b
- Parent:
- 0:39b5762958a4
File content as of revision 1:ace4b3aef52b:
/** * @file checksum.cpp * @brief Utility Function - Data integrity helpers * @author sam grove * @version 1.0 * * Copyright (c) 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "checksum.h" bool validateChecksum( uint8_t const *pkt, uint32_t const length ) { uint32_t pos = 0; uint8_t sum = 0; while ( pos < (length-1) ) { sum += *(pkt+pos++); } sum = 0x0 - sum; // return 0 or 1 based on the checksum test return (sum == *(pkt+pos)) ? 1 : 0; } void calculateChecksum( uint8_t *pkt, uint32_t const length ) { uint32_t pos = 0; uint8_t sum = 0; while ( pos < (length-1) ) { sum += *(pkt+pos++); } // put the checksum into the data stream *(pkt+pos) = 0x0 - sum; return; }