gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:08:57 27 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

上述代码的更快版本是:

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 header 复制到 []byte header 。再次使用 unsafe 包获取指向 []byte 的指针 header并调整转换的长度和容量。

b = *(*[]byte)(unsafe.Pointer(&listOfIntegers))
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
hdr.Len *= 2
hdr.Cap *= 2
protobufObject.ByteStream = b

关于go - 如何将 int 数组快速转换为字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55754621/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com