diff --git a/payload.go b/payload.go index 30bd391..5ffc6d9 100644 --- a/payload.go +++ b/payload.go @@ -251,10 +251,9 @@ func (p *Payload) PackLittleEndian() *big.Int { // Reverse byte array for little endian signals. func reverse(data []byte) []byte { - reversedArray := make([]byte, len(data)) - copy(reversedArray, data) - for i, j := 0, len(reversedArray)-1; i < j; i, j = i+1, j-1 { - reversedArray[i], reversedArray[j] = reversedArray[j], reversedArray[i] + reversedArray := make([]byte, 0, len(data)) + for i := len(data) - 1; i >= 0; i-- { + reversedArray = append(reversedArray, data[i]) } return reversedArray } diff --git a/payload_test.go b/payload_test.go index 1ed28bd..127aa5e 100644 --- a/payload_test.go +++ b/payload_test.go @@ -2,6 +2,7 @@ package can import ( "fmt" + "reflect" "testing" ) @@ -66,6 +67,24 @@ func TestSignedBigEndian(t *testing.T) { fmt.Println(payload.SignedBitsBigEndian(signal.start, signal.length)) } +func TestReverse(t *testing.T) { + payloadHexes := []string{ + "17399b6c89d22805003f", // Even Length + "17399b6c89d22805003f17399b6c89d22805003f17399b6c89d22805003f", // Long Even + "17399b6c89d2280500", // Odd Length + "17399b6c89d228050017399b6c89d228050017399b6c89d2280500", // Long Odd + } + + for _, hex := range payloadHexes { + p, _ := PayloadFromHex(hex) + + twiceReversed := reverse(reverse(p.Data)) + if !reflect.DeepEqual(p.Data, twiceReversed) { + t.Errorf("Reversed slices are not equal, input: %v, output: %v", p.Data, twiceReversed) + } + } +} + func Benchmark4BytesPayload_PackLittleEndian(b *testing.B) { data := []byte{0x40, 0x23, 0x01, 0x12} payload := Payload{Data: data}