字节切片部分复制

huangapple go评论70阅读模式
英文:

Byte slice partial copy

问题

我对Go语言还比较陌生,我正在尝试访问一个字节切片的一部分,并将其复制到另一个固定长度的字节切片,但是找不到正确的解决方案。

我最好的猜测是:

var extracted []byte
var newSlice [512]byte = extracted[0 : 511]

但是这给我一个转换错误:

cannot use extracted[0:511] (value of type []byte) as [512]byte value in variable declarationcompilerIncompatibleAssign

注意:

  • 这将在一个循环中进行,以每次迭代处理512个字节的大小;
  • extracted实际上具有固定大小为512*n字节,但如果我固定该长度,我会遇到相同的问题。

我以为我可以使用io.Reader,但这种方法也失败了。

欢迎任何帮助 字节切片部分复制

英文:

I'm rather new with go and I'm trying to access a portion of a byte slice and copy to a another fixed length byte slice but doesn't find the proper solution.

My best bet was :

var extracted []byte
var newSlice [512]byte = extracted[0 : 511]

But this gives me a conversion error :

cannot use extracted[0:511] (value of type []byte) as [512]byte value in variable declarationcompilerIncompatibleAssign

Notes :

  • this will be in a loop to iterate over the entire size of extracted 512 bytes at a time;
  • extracted actually has a fixed size of 512*n bytes, but if I fix that length I have the same issue

I thought I could use a io.Reader but this approach failed miserably as well.

Any help welcome 字节切片部分复制

答案1

得分: 1

以下是翻译好的内容:

这里有几种方法:

  • 将切片转换为数组指针 并解引用该指针:

    var pixels [512]byte
    pixels = *(*[512]byte)(extracted[:512])
    

    可以使用 短变量声明 在一条语句中完成:

    pixels := *(*[512]byte)(extracted[:512])
    
  • 使用内置的 copy 函数将切片的元素复制到数组中(这一点在问题的评论中已经提到):

    var pixels [512]byte
    copy(pixels[:], extracted[:512])
    
英文:

Here are a couple of approaches:

  • Convert the slice to an array pointer and dereference that pointer:

    var pixels [512]byte
    pixels = *(*[512]byte)(extracted[:512])
    

    This can be done in one statement using a short variable declaration:

    pixels := *(*[512]byte)(extracted[:512])
    
  • Use the builtin copy function to copy elements from a slice to an array (this point was covered in the question comments):

    var pixels [512]byte
    copy(pixels[:], extracted[:512])
    

huangapple
  • 本文由 发表于 2022年9月8日 17:24:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/73646667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定