github.com/la5nta/wl2k-go@v0.11.8/transport/ardop/crc16.go (about)

     1  // Copyright 2015 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
     2  // Use of this source code is governed by the MIT-license that can be
     3  // found in the LICENSE file.
     4  
     5  package ardop
     6  
     7  // CRC-16-CCITT (Reversed reciprocal, 0x8810 polynomial) with 0xffff initial seed
     8  
     9  const polynomial = 0x8810
    10  
    11  func crc16Sum(data []byte) (sum uint16) {
    12  	sum = 0xffff // Initial seed
    13  
    14  	for _, b := range data {
    15  		// For each bit, processing most significant bit first
    16  		for mask := uint16(0x80); mask > 0; mask >>= 1 {
    17  			divisible := (sum & 0x8000) != 0 // Most significant bit is set
    18  
    19  			// Shift left
    20  			sum <<= 1
    21  
    22  			// Bring current data bit onto least significant bit of sum
    23  			dataBit := uint16(b) & mask
    24  			if dataBit != 0 {
    25  				sum += 1
    26  			}
    27  
    28  			// Divide
    29  			if divisible {
    30  				sum ^= polynomial
    31  			}
    32  		}
    33  	}
    34  
    35  	return sum
    36  }