diff --git a/internal/utils/byteoder_big_endian_test.go b/internal/utils/byteoder_big_endian_test.go index 5d0873a9..6055e8d5 100644 --- a/internal/utils/byteoder_big_endian_test.go +++ b/internal/utils/byteoder_big_endian_test.go @@ -9,6 +9,23 @@ import ( ) var _ = Describe("Big Endian encoding / decoding", func() { + Context("converting", func() { + It("Uint16", func() { + b := []byte{0x13, 0x37} + Expect(BigEndian.Uint16(b)).To(Equal(uint16(0x1337))) + }) + + It("Uint24", func() { + b := []byte{0x13, 0x99, 0x37} + Expect(BigEndian.Uint24(b)).To(Equal(uint32(0x139937))) + }) + + It("Uint32", func() { + b := []byte{0xde, 0xad, 0xbe, 0xef} + Expect(BigEndian.Uint32(b)).To(Equal(uint32(0xdeadbeef))) + }) + }) + Context("ReadUint16", func() { It("reads a big endian", func() { b := []byte{0x13, 0xEF} diff --git a/internal/utils/byteorder.go b/internal/utils/byteorder.go index d1f52842..a9b715e2 100644 --- a/internal/utils/byteorder.go +++ b/internal/utils/byteorder.go @@ -7,6 +7,10 @@ import ( // A ByteOrder specifies how to convert byte sequences into 16-, 32-, or 64-bit unsigned integers. type ByteOrder interface { + Uint32([]byte) uint32 + Uint24([]byte) uint32 + Uint16([]byte) uint16 + ReadUint32(io.ByteReader) (uint32, error) ReadUint24(io.ByteReader) (uint32, error) ReadUint16(io.ByteReader) (uint16, error) diff --git a/internal/utils/byteorder_big_endian.go b/internal/utils/byteorder_big_endian.go index d05542e1..834a711b 100644 --- a/internal/utils/byteorder_big_endian.go +++ b/internal/utils/byteorder_big_endian.go @@ -2,6 +2,7 @@ package utils import ( "bytes" + "encoding/binary" "io" ) @@ -73,6 +74,19 @@ func (bigEndian) ReadUint16(b io.ByteReader) (uint16, error) { return uint16(b1) + uint16(b2)<<8, nil } +func (bigEndian) Uint32(b []byte) uint32 { + return binary.BigEndian.Uint32(b) +} + +func (bigEndian) Uint24(b []byte) uint32 { + _ = b[2] // bounds check hint to compiler; see golang.org/issue/14808 + return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16 +} + +func (bigEndian) Uint16(b []byte) uint16 { + return binary.BigEndian.Uint16(b) +} + // WriteUint32 writes a uint32 func (bigEndian) WriteUint32(b *bytes.Buffer, i uint32) { b.Write([]byte{uint8(i >> 24), uint8(i >> 16), uint8(i >> 8), uint8(i)})