Encode binary, base64 and hex
Encode binary, base64 and hex
Binary formats require an explicit byte order and field width. BigEndian places the most significant byte first; LittleEndian places it last. Base64 and hexadecimal represent arbitrary bytes as text. Neither encrypts data, and neither provides integrity protection.
package main
import ( "encoding/binary" "fmt")
func main() { b := make([]byte, 2) binary.BigEndian.PutUint16(b, 258) fmt.Printf("%x %d\n", b, binary.BigEndian.Uint16(b)) binary.LittleEndian.PutUint16(b, 258) fmt.Printf("%x %d\n", b, binary.LittleEndian.Uint16(b))}258 equals 0x0102. PutUint16 and Uint16 require at least two bytes and can panic on a short slice. Check length before reading external input and agree on endianness with the sender. Use fixed-width numeric types for portable binary layouts.
Expected output:
0102 2580201 258Text encodings for arbitrary bytes
package main
import ( "bytes" "encoding/base64" "encoding/hex" "fmt")
func check(e error) { if e != nil { panic(e) }}
func main() { b := []byte{0, 255, 16} s := base64.StdEncoding.EncodeToString(b) h := hex.EncodeToString(b) a, e := base64.StdEncoding.DecodeString(s) check(e) c, e := hex.DecodeString(h) check(e) fmt.Println(s, h) fmt.Println(bytes.Equal(a, c), bytes.Equal(a, b))}Hex uses two characters per byte. Standard padded base64 uses four characters per three bytes, rounding up for a final partial group. URL-safe and raw variants differ in alphabet or padding; agree on the exact variant. Reject decode errors, even if a decoder returned some bytes before the error.
Expected output:
AP8Q 00ff10true trueTry it locally
Encode uint16 value 513 into a two-byte big-endian slice, then print its hex representation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Serialization 08: Encode binary, base64 and hex
Check the lesson objective before moving on.
What bytes represent 258 as uint16 big-endian?
Does base64 protect a secret from someone reading it?