Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of a byte array golang

Tags:

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?

like image 621
sr_149 Avatar asked Jul 30 '15 20:07

sr_149


People also ask

What is [] uint8 in Golang?

type uint8 in Golang is the set of all unsigned 8-bit integers. The set ranges from 0 to 255. You should use type uint8 when you strictly want a positive integer in the range 0-255.

What is byte slice?

Byte slices are a list of bytes that represent UTF-8 encodings of Unicode code points. Taking the information from above, we could create a byte slice that represents the word “Go”: bs := []byte{71, 111}


2 Answers

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.

like image 100
Caleb Avatar answered Sep 23 '22 05:09

Caleb


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.

like image 10
evanmcdonnal Avatar answered Sep 24 '22 05:09

evanmcdonnal