THAMER
Sovereign Bitcoin Wallet

WALLET AI BITCOIN

Your Bitcoin Wallet. Your Keys. Your Engine.

Self-hosted Bitcoin software built for developers, applications, and AI agents.

CREATE WALLET

Bitcoin Serialization and Little-Endian Encoding in Go

permalink THAMER
#bitcoin#bitcoin-development#bitcoin-script#golang

GOLANG + BITCOIN SCRIPT — Stage 001, Lesson 06 of 12.

Concept

Many Bitcoin transaction fields use little-endian fixed-width encoding. The integer 500 is 0x000001f4, serialized as f4010000 in four bytes. This does not imply that every field in Bitcoin uses the same encoding: CompactSize integers, scripts and hashes have their own rules.

Engineering practice

Use binary.LittleEndian.PutUint32 with an explicitly sized buffer. Avoid serializing Go structs by copying memory, because padding and native byte order are not protocol definitions. The test asserts the exact four bytes. Later stages will cover CompactSize and complete wire transactions.

Source example

Go · 9 lines
1package main
2
3import (
4	"encoding/binary"
5	"fmt"
6)
7
8func encode(v uint32) [4]byte { var b [4]byte; binary.LittleEndian.PutUint32(b[:], v); return b }
9func main()                   { fmt.Printf("%x\n", encode(500)) }

Run locally

From the 001-foundations directory:

go test ./02-serialization
go run ./02-serialization

Regression test

Go · 11 lines
1package main
2
3import (
4	"testing"
5)
6
7func TestExample(t *testing.T) {
8	if encode(500) != [4]byte{244, 1, 0, 0} {
9		t.Fatal("wrong encoding")
10	}
11}

Exercise

Encode 1 and 256, then compare their byte order.

Reference

https://developer.bitcoin.org/reference/transactions.html

Series navigation

https://thamer.org/learn/bitcoin-development-libraries-go

Previous lesson:
https://thamer.org/learn/bitcoin-bytes-hex-go

Next lesson:
https://thamer.org/learn/bitcoin-satoshis-amounts-go

Questions & Answers

Explore all questions →

Latest from the Lab

THAMER illustrated developer portrait and signature

ABOUT THE DEVELOPER

Independent Software Developer specializing in Bitcoin Script, Golang, and AI Agents.

Software engineering · Independent research · Open-source projects