如何将int数组快速转换为字节数组?

问题描述 投票:1回答:1

我有一个过程需要每隔几毫秒将一大堆qazxswpos打包到一个protobuf。理解它的protobuf方面并不重要,因为我真正需要的是将一堆int16s(160-16k)转换为int16的方法。这是一个关键的CPU操作,所以我不想做这样的事情:

[]byte

(如果你有兴趣,这是protobuf)

for _, sample := range listOfIntegers {
  protobufObject.ByteStream = append(protobufObject.Bytestream, byte(sample>>8))
  protobufObject.ByteStream = append(protobufObject.Bytestream, byte(sample&0xff))
}

必须有一种更快的方法来将整数列表作为内存块提供给protobuf。我已经摆弄了cgo库来访问memcpy,但怀疑我一直在破坏底层的go数据结构,因为我在完全不相关的代码段中崩溃了。

go type-conversion memcpy
1个回答
1
投票

以上代码的更快版本是:

message ProtobufObject {
  bytes byte_stream = 1;
  ...               = 2;
  etc.
}

在big-endian体系结构上运行时,可以避免复制数据。

使用protobufObject.ByteStream := make([]byte, len(listOfIntegers) * 2) for i, n := range listOfIntegers { j := i * 2 protobufObject.ByteStream[j+1] = byte(n) protobufObject.ByteStream[j] = byte(n>>8) } 包将unsafe标头复制到[]int16标头。再次使用unsafe包来获取指向[]byte []byte的指针并调整转换的长度和容量。

header
© www.soinside.com 2019 - 2024. All rights reserved.