【问题标题】:How to turn a slice of Uint64 into a slice of Bytes如何将 Uint64 的切片变成 Bytes 的切片
【发布时间】:2016-07-24 12:30:20
【问题描述】:

我目前有一个如下所示的 protobuf 结构:

type RequestEnvelop_MessageQuad struct {
    F1   [][]byte `protobuf:"bytes,1,rep,name=f1,proto3" json:"f1,omitempty"`
    F2   []byte   `protobuf:"bytes,2,opt,name=f2,proto3" json:"f2,omitempty"`
    Lat  float64  `protobuf:"fixed64,3,opt,name=lat" json:"lat,omitempty"`
    Long float64  `protobuf:"fixed64,4,opt,name=long" json:"long,omitempty"`
}

F1 获取一些我生成的 S2 几何数据,如下所示:

ll := s2.LatLngFromDegrees(location.Latitude, location.Longitude)
cid := s2.CellIDFromLatLng(ll).Parent(15)
walkData := []uint64{cid.Pos()}

next := cid.Next()
prev := cid.Prev()

// 10 Before, 10 After
for i := 0; i < 10; i++ {
    walkData = append(walkData, next.Pos())
    walkData = append(walkData, prev.Pos())

    next = next.Next()
    prev = prev.Prev()
}

log.Println(walkData)

唯一的问题是,protobuf 结构需要[][]byte 类型我只是不确定如何将uint64 数据转换为字节。谢谢。

【问题讨论】:

    标签: go


    【解决方案1】:

    可以使用标准库中的encoding/binary 包将整数值编码为字节数组。

    例如,要将uint64 编码为字节缓冲区,我们可以使用binary.PutUvarint 函数:

    big := uint64(257)
    buf := make([]byte, 2)
    n := binary.PutUvarint(buf, big)
    fmt.Printf("Wrote %d bytes into buffer: [% x]\n", n, buf)
    

    哪个会打印:

    Wrote 2 bytes into buffer: [81 02]
    

    我们还可以使用binary.Write 函数将通用流写入缓冲区:

    buf := new(bytes.Buffer)
    var pi float64 = math.Pi
    err := binary.Write(buf, binary.LittleEndian, pi)
    if err != nil {
        fmt.Println("binary.Write failed:", err)
    }
    fmt.Printf("% x", buf.Bytes())
    

    哪些输出:

    18 2d 44 54 fb 21 09 40
    

    (第二个示例是从该软件包文档中借用的,您可以在其中找到其他类似示例)

    【讨论】:

      猜你喜欢
      • 2019-09-09
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 2021-10-28
      • 2020-11-08
      相关资源
      最近更新 更多