Skip to content

Instantly share code, notes, and snippets.

@smoser
Created February 12, 2020 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smoser/e2c29a49587319a57506e3c9b89b5ca7 to your computer and use it in GitHub Desktop.
Save smoser/e2c29a49587319a57506e3c9b89b5ca7 to your computer and use it in GitHub Desktop.
little endian / big endian things

little endian conversion

I was working on gpt package in go and I didn't realize that the author had handled conversion to little endian when writing header.

I was under the impression that I had to create the header with the little endian value.

For example, the Size of a standard header is 92 bytes. I didn't want to deal with writing:

Header {
    Size: binary.LittleEndian.Uint32([]byte{0x5C, 0x00, 0x00, 0x00}),
}

I wanted to just type type 92 to improve readability.

So I wrote these functions such that I could do:

Header {
    Size: leUint32(92)
}

In the end, it was a waste of my time.

package main
import (
"bytes"
"encoding/binary"
"testing"
)
const standardHeaderSize = 92
const standardPartitionEntrySize = 128
func leUint32(n uint32) uint32 {
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, n)
return binary.LittleEndian.Uint32(b)
}
func leUint64(n uint64) uint64 {
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, n)
return binary.LittleEndian.Uint64(b)
}
func TestLeUint32(t *testing.T) {
for _, d := range []struct {
input uint32
expected []byte
}{
{0, []byte{0x00, 0x00, 0x00, 0x00}},
{standardHeaderSize, []byte{0x5c, 0x00, 0x00, 0x00}},
{standardPartitionEntrySize, []byte{0x80, 0x00, 0x00, 0x00}},
{65536, []byte{0x00, 0x00, 0x01, 0x00}},
{1953525134, []byte{0x8e, 0x6d, 0x70, 0x74}},
} {
asUint32 := leUint32(d.input)
buf := make([]byte, 4)
binary.LittleEndian.PutUint32(buf, asUint32)
if bytes.Compare(buf, d.expected) != 0 {
t.Errorf("leUint32(%d) found bytes as %v expected %v",
d.input, buf, d.expected)
}
}
}
// TestLeUint64 -
func TestLeUint64(t *testing.T) {
for _, d := range []struct {
input uint64
expected []byte
}{
{0, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{standardHeaderSize, []byte{0x5c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{standardPartitionEntrySize, []byte{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{65536, []byte{0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}},
{uint64(4294967296), []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00}},
} {
asUint64 := leUint64(d.input)
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, asUint64)
if bytes.Compare(buf, d.expected) != 0 {
t.Errorf("leUint64(%d) found bytes as %v expected %v",
d.input, buf, d.expected)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment