xref: /aosp_15_r20/external/vboot_reference/firmware/2lib/2crc8.c (revision 8617a60d3594060b7ecbd21bc622a7c14f3cf2bc)
1 /* Copyright 2014 The ChromiumOS Authors
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  *
5  * Very simple 8-bit CRC function.
6  */
7 
8 #include "2crc8.h"
9 #include "2sysincludes.h"
10 
11 /* Uses CRC-8 ITU version, with x^8 + x^2 + x + 1 polynomial.
12    Note that result will evaluate to zero for a buffer of all zeroes. */
vb2_crc8(const void * vptr,uint32_t size)13 uint8_t vb2_crc8(const void *vptr, uint32_t size)
14 {
15 	const uint8_t *data = vptr;
16 	unsigned crc = 0;
17 	uint32_t i, j;
18 
19 	/* Calculate CRC-8 directly.  A table-based algorithm would be faster,
20 	   but for only a few bytes it isn't worth the code size. */
21 	for (j = size; j; j--, data++) {
22 		crc ^= (*data << 8);
23 		for (i = 8; i; i--) {
24 			if (crc & 0x8000)
25 				crc ^= (0x1070 << 3);
26 			crc <<= 1;
27 		}
28 	}
29 
30 	return (uint8_t)(crc >> 8);
31 }
32