-
Notifications
You must be signed in to change notification settings - Fork 6
/
crc32.go
47 lines (42 loc) · 1.05 KB
/
crc32.go
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
package cuei
import (
"fmt"
)
const zero = 0x00
const one = 0x01
const eight = 0x08
const twentyFour = 0x18
const twoFiftyFive = 0xFF
const twoFiftySix = 0x100
const mask = 0x80000000 // Crc32 mask
const initValue = 0xFFFFFFFF // initial Crc32 value
const initPoly = 0x104C11DB7 // Polynomial value for cRC32 table
// bytecrc creates the values used to populate the table
func bytecrc(crc int, aPoly int) int {
for i := 0; i < eight; i++ {
if crc&mask != zero {
crc = crc<<one ^ aPoly
} else {
crc = crc << one
}
}
return int(crc & initValue)
}
// mkTable makes the Crc32 table
func mkTable() [twoFiftySix]int {
var tbl [twoFiftySix]int
newPoly := initPoly & initValue
for idx := range tbl {
tbl[idx] = bytecrc((idx << twentyFour), newPoly)
}
return tbl
}
// MkCrc32 generate a 32 bit Crc as hex
func MkCrc32(data []byte) string {
crc := initValue
tbl := mkTable()
for _, bite := range data {
crc = tbl[int(bite)^((crc>>twentyFour)&twoFiftyFive)] ^ ((crc << eight) & (initValue - twoFiftyFive))
}
return fmt.Sprintf("%#x", uint32(crc))
}