Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle odd length crc values #8

Merged
merged 1 commit into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading