Understanding Bytes and Hex in Bitcoin
GOLANG + BITCOIN SCRIPT — Stage 001, Lesson 05 of 12.
Concept
Hex is a textual representation of bytes, not encryption. Two hex characters encode one byte. The string 00ff10 represents three bytes, including a leading zero. Treating it as an integer can lose that leading zero and change a serialized message.
Engineering practice
encoding/hex.DecodeString returns bytes and an error. Reject malformed input instead of using partially decoded data. Odd-length strings and non-hex characters are invalid. The example prints 00ff10 followed by a nil error; its test checks valid bytes and rejects xyz.
Source example
1package main
2
3import (
4 "encoding/hex"
5 "fmt"
6)
7
8func decode(s string) ([]byte, error) { return hex.DecodeString(s) }
9func main() { v, e := decode("00ff10"); fmt.Printf("%x %v\n", v, e) }Run locally
From the 001-foundations directory:
go test ./01-hex
go run ./01-hex
Regression test
1package main
2
3import (
4 "testing"
5)
6
7func TestExample(t *testing.T) {
8 v, e := decode("00ff10")
9 if e != nil || len(v) != 3 || v[1] != 255 {
10 t.Fatal(v, e)
11 }
12 if _, e = decode("xyz"); e == nil {
13 t.Fatal("invalid hex accepted")
14 }
15}Exercise
Try 0001 and an odd-length string; explain why the leading zero must survive.
Reference
https://pkg.go.dev/encoding/hex
Series navigation
https://thamer.org/learn/bitcoin-development-libraries-go
Previous lesson:
https://thamer.org/learn/migrating-btcsuite-v2-modules
Next lesson:
https://thamer.org/learn/bitcoin-serialization-little-endian-go
