Run-Length Encoding Round Trip
Run-length encoding appends each run's count after its byte, and decoding rebuilds the original text only when every count was written back.
Code
package main
import (
"fmt"
"strconv"
)
// run-length encoding: each run is written as the character plus its repeat count
func encode(s string) string {
if s == "" {
return ""
}
out := make([]byte, 0, len(s))
count := 1
for i := 1; i < len(s); i++ {
if s[i] == s[i-1] {
count++
continue
}
out = append(out, s[i-1])
out = append(out, strconv.Itoa(count)...)
count = 1
}
out = append(out, s[len(s)-1])
out = append(out, strconv.Itoa(count)...)
return string(out)
}
// round trip: expands runs back to the original; safe only when the input has no digits
func decode(s string) (string, error) {
var out []byte
count := 0
for i := 0; i < len(s); i++ {
ch := s[i]
if ch >= '0' && ch <= '9' {
count = count*10 + int(ch-'0')
continue
}
if count == 0 {
return "", fmt.Errorf("missing count before %q", ch)
}
for j := 0; j < count; j++ {
out = append(out, ch)
}
count = 0
}
if count != 0 {
return "", fmt.Errorf("dangling count %d", count)
}
return string(out), nil
}
func main() {
raw := "aaabbbccccd"
packed := encode(raw)
fmt.Println("encoded:", packed)
back, err := decode(packed)
fmt.Println("decoded:", back, "err:", err)
}How the snippet works
Under the hood: the functions encode, decode and main.
Repetition is confined to for i := 1; i < len(s); i++ — the rest of the file is straight-line.
Points of care
- Built-in APIs only — no supply chain needs to be vetted.
Using it
The primary signature, spelled out, is func encode(s string) string
The run prints labeled output — encoded:, decoded: — when the file runs.
main calls 2 helpers in sequence: encode and decode.
The key statements, annotated
return "", fmt.Errorf("missing count before %q", ch)
return "", fmt.Errorf("dangling count %d", count)
func main() {
raw := "aaabbbccccd"
packed := encode(raw)
fmt.Println("encoded:", packed)
back, err := decode(packed)
fmt.Println("decoded:", back, "err:", err)
}
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- What does Run-Length Encoding Round Trip print when run?
- Running the file directly is enough — expect labeled output lines such as `encoded:`, `decoded:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.