我正在做一些整数压缩的工作。
我已经在C++中实现了可变字节编码算法(请参阅下面的代码片段)。如何在golang中实现可变字节编码算法

intstringtunememcpy()
binary.Write()encoding/binary

但如何编码一个整数,介于2097152和268435456之间,只使用3个字节?

有没有类似的片段转换方法?

void encode(int value, char* code_list, int& len) { 

    int bit_value = http://cn.voidcc.com/question/0; 
    int bit_num = 0; 

    if (value < 128) { 
    bit_num = 1; 
    } else if (value < 16384) { 
    bit_num = 2; 
    bit_value = 1; 
    } else if (value < 2097152) { 
    bit_num = 3; 
    bit_value = 3; 
    } else { 
    bit_num = 4; 
    bit_value = 7; 
    } 
    value <<= bit_num; 
    value += bit_value; 
    memcpy(code_list + len, (char*) &value, bit_num); 
    len += bit_num; 

} 

Will

回答

1
io.Writermemcpy

看到它运行在:https://play.golang.org/p/jr0NypSnlW

package main 

import (
    "fmt" 
    "bytes" 
    "io" 
) 

func encode(w io.Writer, n uint64) error { 
    bytes := 0 
    switch { 
    case n < 128: 
     bytes = 1 
     n = (n << 1) 
    case n < 16834: 
     bytes = 2 
     n = (n << 2) | 1 
    case n < 2097152: 
     bytes = 3 
     n = (n << 3) | 3 
    default: 
     bytes = 4 
     n = (n << 4) | 7 
    } 
    d := [4]byte{ 
     byte(n), byte(n>>8), byte(n>>16), byte(n>>24), 
    } 
    _, err := w.Write(d[:bytes]) 
    return err 
} 

func main() { 
    xs := []uint64{0, 32, 20003, 60006, 300009} 
    var b bytes.Buffer 
    for _, x := range xs { 
     if err := encode(&b, x); err != nil { 
      panic(err) 
     } 
    } 
    fmt.Println(b.Bytes()) 
} 

知道了,谢谢。 –