相当于 PHP 的 pack()?

Go equivalent for PHP's pack()?

在 PHP 中,要对整数、浮点数等二进制数据进行编码,我会执行以下操作:

<?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

如何将此代码引入 Go?

为什么您需要在 pack() 中的类型已经是语言本身的本地类型的语言中使用 pack() 之类的函数?

要对二进制数据进行编码,您需要使用包 encoding/binary。要复制您的代码:

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)

有了它,开始对其他数据结构进行编码就相当容易了。您真的只需要将 binary.Write 的第三个参数更改为您想要的数据类型,函数就会执行 all the magic

这不是一个完整的答案,但由于我自己一直在寻找以下内容,我认为它也可以帮助其他人。

对于 php 的 bin2hex() 的直接等价物,您可以这样做:

import "encoding/hex"

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