morganbaz
morganbaz

Reputation: 3117

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?

Upvotes: 1

Views: 2351

Answers (2)

Abu Junayd
Abu Junayd

Reputation: 115

This is not a complete answer, but since I've been looking for the following myself, I thought it could help others here too.

For a direct equivalent of php's bin2hex(), you can do:

import "encoding/hex"

func bin2hex(str string) string {
  return hex.EncodeToString([]byte(str))
}

Upvotes: 0

morganbaz
morganbaz

Reputation: 3117

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!

Upvotes: 4

Related Questions