dongsi3826 2019-04-18 22:50
浏览 190

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

I have a process that needs to pack a large array of int16s to a protobuf every few milliseconds. Understanding the protobuf side of it isn't critical, since all I really need is a way to convert a bunch of int16s (160-16k of them) to []byte. It's a CPU-critical operation, so I don't want to do something like this:

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

(If you're interested, this is the protobuf)

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

There has to be a faster way to supply that list of ints as a block of memory to the protobuf. I've fiddled with the cgo library to get access to memcpy, but suspect I've been destroying an underlying go data structure because I get crashes in totally unrelated sections of code.

  • 写回答

1条回答 默认 最新

  • dongnai2804 2019-04-19 02:53
    关注

    A faster version of the above code is:

    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)
    }
    

    You can avoid copying the data when running on a big-endian architecture.

    Use the unsafe package to copy the []int16 header to the []byte header. Use the unsafe package again to get a pointer to the []byte header and adjust the length and capacity for the conversion.

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

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决