dongzhui9936 2010-01-29 03:58
浏览 68
已采纳

使用Go,如何将未知数量的字节追加到向量中并获取字节切片?

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 import (
  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.

  • 写回答

3条回答 默认 最新

  • doulan0297 2010-01-29 04:55
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染