Size of a byte array golang

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

Size of a byte array golang

问题

我有一个 []byte 对象,我想要获取它的字节大小。在 golang 中是否有类似于 C 语言的 sizeof() 函数的等价物?如果没有,你能否提供其他获取相同结果的方法?

英文:

I have a []byte object and I want to get the size of it in bytes. Is there an equivalent to C's sizeof() in golang? If not, Can you suggest other ways to get the same?

答案1

得分: 32

要返回字节切片中的字节数,可以使用len函数:

bs := make([]byte, 1000)
sz := len(bs)
// sz == 1000

如果你指的是底层数组中的字节数,请使用cap

bs := make([]byte, 1000, 2000)
sz := cap(bs)
// sz == 2000

一个字节保证是一个字节大小:https://golang.org/ref/spec#Size_and_alignment_guarantees。

英文:

To return the number of bytes in a byte slice use the len function:

bs := make([]byte, 1000)
sz := len(bs)
// sz == 1000

If you mean the number of bytes in the underlying array use cap instead:

bs := make([]byte, 1000, 2000)
sz := cap(bs)
// sz == 2000

A byte is guaranteed to be one byte: https://golang.org/ref/spec#Size_and_alignment_guarantees.

答案2

得分: 11

我认为你最好的选择是:

package main

import "fmt"
import "encoding/binary"

func main() {
    thousandBytes := make([]byte, 1000)
    tenBytes := make([]byte, 10)
    fmt.Println(binary.Size(tenBytes))
    fmt.Println(binary.Size(thousandBytes))
}

虽然有很多选项,比如只导入unsafe包并使用sizeof

import unsafe "unsafe"

size := unsafe.Sizeof(bytes)

请注意,对于某些类型(如切片),Sizeof将给出切片描述符的大小,这可能不是你想要的。此外,请记住切片的长度和容量是不同的,而binary.Size返回的值反映的是长度。

英文:

I think your best bet would be;

package main

import "fmt"
import "encoding/binary"

func main() {
	thousandBytes := make([]byte, 1000)
	tenBytes := make([]byte, 10)
	fmt.Println(binary.Size(tenBytes))
	fmt.Println(binary.Size(thousandBytes))
}

https://play.golang.org/p/HhJif66VwY

Though there are many options, like just importing unsafe and using sizeof;

import unsafe "unsafe"

size := unsafe.Sizeof(bytes)

Note that for some types, like slices, Sizeof is going to give you the size of the slice descriptor which is likely not what you want. Also, bear in mind the length and capacity of the slice are different and the value returned by binary.Size reflects the length.

huangapple
  • 本文由 发表于 2015年7月31日 04:11:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/31733145.html
匿名

发表评论

匿名网友

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

确定