开发者

With Go, how to append unknown number of byte into a vector and get a slice of bytes?

I'm trying to encode a large number to a list of bytes(uint8 in Go). The number of bytes is unknown, so I'd like to use vector. But Go doesn't provide vector of byte, what can I do? And is it possible to get a slice of such a byte vector?

I intends to implement data compression. Instead of store small and large number with the same number of bytes, I'm implements a variable bytes that uses less bytes with small number and more bytes with large number.

My code can not compile, invalid type assertion:

  1 package main
  2 
  3 imp开发者_StackOverflow社区ort (
  4     //"fmt"
  5     "container/vector"
  6 )
  7 
  8 func vbEncodeNumber(n uint) []byte{
  9     bytes := new(vector.Vector)
 10     for {
 11         bytes.Push(n % 128)
 12         if n < 128 {
 13             break
 14         }
 15         n /= 128
 16     }
 17     bytes.Set(bytes.Len()-1, bytes.Last().(byte)+byte(128))
 18     return bytes.Data().([]byte) // <-
 19 }
 20 
 21 func main() { vbEncodeNumber(10000) }

I wish to writes a lot of such code into binary file, so I wish the func can return byte array.

I haven't find a code example on vector.


Since you're trying to represent large numbers, you might see if the big package serves your purposes.

The general Vector struct can be used to store bytes. It accepts an empty interface as its type, and any other type satisfies that interface. You can retrieve a slice of interfaces through the Data method, but there's no way to convert that to a slice of bytes without copying it. You can't use type assertion to turn a slice of interface{} into a slice of something else. You'd have to do something like the following at the end of your function: (I haven't tried compiling this code because I can't right now)

byteSlice = make([]byte, bytes.Len())
for i, _ := range byteSlice {
    byteSlice[i] = bytes.At(i).(byte)
}
return byteSlice


Take a look at the bytes package and the Buffer type there. You can write your ints as bytes into the buffer and then you can use the Bytes() method to access byte slices of the buffer.


I've found the vectors to be a lot less useful since the generic append and copy were added to the language. Here's how I'd do it in one shot with less copying:

package main

import "fmt"

func vbEncodeNumber(n uint) []byte {
    bytes := make([]byte, 0, 4)
    for n > 0 {
        bytes = append(bytes, byte(n%256))
        n >>= 8
    }
    return bytes
}

func main() {
    bytes := vbEncodeNumber(10000)
    for i := len(bytes)-1; i >= 0 ; i-- {
        fmt.Printf("%02x ", bytes[i])
    }
    fmt.Println("")
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜