aboutsummaryrefslogtreecommitdiffstats
path: root/libcrcgen/reference.py
blob: 4e790749969dbc4ae425684861fcb1eb91783e9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# vim: ts=8 sw=8 noexpandtab
#
#   CRC code generator
#
#   Copyright (c) 2019-2023 Michael Büsch <m@bues.ch>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License along
#   with this program; if not, write to the Free Software Foundation, Inc.,
#   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

__all__ = [
	"CrcReference",
]

from typing import Iterable

class CrcReference:
	"""Generic CRC reference implementation.
	"""

	@classmethod
	def crc(cls,
		crc: int,
		data: int,
		polynomial: int,
		nrCrcBits: int,
		nrDataBits: int = 8,
		shiftRight: bool = False):

		crcMask = (1 << nrCrcBits) - 1
		msb = 1 << (nrCrcBits - 1)
		lsb = 1
		if shiftRight:
			for i in range(nrDataBits):
				crc ^= data & 1
				data >>= 1
				if crc & lsb:
					crc = ((crc >> 1) ^ polynomial) & crcMask
				else:
					crc = (crc >> 1) & crcMask
		else:
			for i in range(nrDataBits):
				crc ^= ((data >> (nrDataBits - 1)) & 1) << (nrCrcBits - 1)
				data <<= 1
				if crc & msb:
					crc = ((crc << 1) ^ polynomial) & crcMask
				else:
					crc = (crc << 1) & crcMask
		return crc

	@classmethod
	def crcBlock(cls,
		     crc: int,
		     data: Iterable,
		     polynomial: int,
		     nrCrcBits: int,
		     nrDataBits: int = 8,
		     shiftRight: bool = False,
		     preFlip: bool  = False,
		     postFlip: bool = False):

		crcMask = (1 << nrCrcBits) - 1
		if preFlip:
			crc ^= crcMask
		for b in data:
			crc = cls.crc(crc=crc,
				      data=b,
				      polynomial=polynomial,
				      nrCrcBits=nrCrcBits,
				      nrDataBits=nrDataBits,
				      shiftRight=shiftRight)
		if postFlip:
			crc ^= crcMask
		return crc
bues.ch cgit interface