dongou0524 2016-02-28 19:39
浏览 32
已采纳

是否等效于PHP的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) . "
"; // 8d680100
echo "uint16: " . bin2hex($uint16) . "
"; // ffff
echo "float: " . bin2hex($float) . "
"; // 52499d3a

How can I bring this code into Go?

  • 写回答

2条回答 默认 最新

  • dongyi1441 2016-02-28 19:39
    关注

    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
    ", buf.Bytes())
    
        buf.Reset()
        binary.Write(buf, byteOrder, uint16(65535))
        fmt.Printf("uint16: %x
    ", buf.Bytes())
    
        buf.Reset()
        binary.Write(buf, byteOrder, float32(0.0012))
        fmt.Printf("float: %x
    ", 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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch