Search code examples
gobinarypack

Go equivalent for PHP's pack()?


In PHP, to encode binary data, such as integers, floats and so on, I'd do the following:

<?php

$uint32 = pack("V", 92301);
$uint16 = pack("v", 65535);
$float = pack("f", 0.0012);

echo "uint32: " . bin2hex($uint32) . "\n"; // 8d680100
echo "uint16: " . bin2hex($uint16) . "\n"; // ffff
echo "float: " . bin2hex($float) . "\n"; // 52499d3a

How can I bring this code into Go?


Solution

  • Why would you need to use a function such as pack() in a language where the types in pack() are already native types of the language itself?

    To encode binary data you'd use the package encoding/binary. To replicate your code:

    package main
    
    import (
        "bytes"
        "encoding/binary"
        "fmt"
    )
    
    func main() {
        buf := new(bytes.Buffer)
        byteOrder := binary.LittleEndian
    
        binary.Write(buf, byteOrder, uint32(92301))
        fmt.Printf("uint32: %x\n", buf.Bytes())
    
        buf.Reset()
        binary.Write(buf, byteOrder, uint16(65535))
        fmt.Printf("uint16: %x\n", buf.Bytes())
    
        buf.Reset()
        binary.Write(buf, byteOrder, float32(0.0012))
        fmt.Printf("float: %x\n", buf.Bytes())
    }
    

    (playground)

    With that, it's fairly easy to get going encoding other data structures. You really just need to change the third argument of binary.Write to be of the data type you wish, and the function will do all the magic!