Skip to content

Commit

Permalink
Handle odd length crc values
Browse files Browse the repository at this point in the history
  • Loading branch information
mnightingale committed Aug 9, 2024
1 parent 4e1d28e commit 54b62f4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
24 changes: 13 additions & 11 deletions decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -454,19 +454,21 @@ func extractCRC(data, substr []byte) (uint32, error) {
}

data = data[start+len(substr):]
dec, err := hex.DecodeString(string(data))
if len(dec) == 4 {
return binary.BigEndian.Uint32(dec), err
end := bytes.IndexAny(data, "\x00\x20\r\n")
if end != -1 {
data = data[:end]
}

// Last 4 bytes to handle some broken encoders
dec = dec[max(0, len(dec)-4):]
if len(dec) == 4 {
return binary.BigEndian.Uint32(dec), nil
// Take up to the last 8 characters
parsed := data[len(data)-min(8, len(data)):]

// Left pad unexpected length with 0
if len(parsed) != 8 {
padded := []byte("00000000")
copy(padded[8-len(parsed):], parsed)
parsed = padded
}

// Pad to 4 bytes length
buf := make([]byte, 4)
copy(buf[4-len(dec):], dec)
return binary.BigEndian.Uint32(buf), nil
_, err := hex.Decode(parsed, parsed)
return binary.BigEndian.Uint32(parsed), err
}
10 changes: 10 additions & 0 deletions decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,23 @@ func TestExtractCRC(t *testing.T) {
expected uint32
}{
{"ffffffffa95d3e50", 0xa95d3e50},
{"fffffffa95d3e50", 0xa95d3e50},
{"ffffffa95d3e50", 0xa95d3e50},
{"fffffa95d3e50", 0xa95d3e50},
{"ffffa95d3e50", 0xa95d3e50},
{"fffa95d3e50", 0xa95d3e50},
{"ffa95d3e50", 0xa95d3e50},
{"fa95d3e50", 0xa95d3e50},
{"a95d3e50", 0xa95d3e50},
{"a95d3e5", 0xa95d3e5},
{"a95d3e", 0xa95d3e},
{"a95d3", 0xa95d3},
{"a95d", 0xa95d},
{"a95", 0xa95},
{"a9", 0xa9},
{"a", 0xa},
{"", 0},
{"12345678 ", 0x12345678}, // space at end
}

for _, tc := range cases {
Expand Down

0 comments on commit 54b62f4

Please sign in to comment.