funcIntToBytes(a int)([]byte,error){if a > math.MaxInt32 {returnnil, errors.New(fmt.Sprintf("a>math.MaxInt32, a is %d\n", a))}
buf :=make([]byte,4)for i :=0; i <4; i++{var b uint8=uint8(a &0xff)
buf[i]= b
a = a >>8}return buf,nil}funcBytesToInt(buf []byte)(int,error){iflen(buf)!=4{return-1, errors.New(fmt.Sprintf("BytesToInt len(buf) must be 4, but got %d\n",len(buf)))}
result :=0for i :=0; i <4; i++{
result +=int(buf[i])<<(8* i)}return result,nil}
AppendVarint
protobuf源码里的转换代码,代码路径 google.golang.org\protobuf@v1.28.0\encoding\protowire\wire.go
返回转换完成的byte数组与数组长度
// AppendVarint appends v to b as a varint-encoded uint64.funcAppendVarint(b []byte, v uint64)([]byte,int){
s :=0for i := v; i >0; s++{
i = i >>8}switch{case v <1<<7:
b =append(b,byte(v))case v <1<<14:
b =append(b,byte((v>>0)&0x7f|0x80),byte(v>>7))case v <1<<21:
b =append(b,byte((v>>0)&0x7f|0x80),byte((v>>7)&0x7f|0x80),byte(v>>14))case v <1<<28:
b =append(b,byte((v>>0)&0x7f|0x80),byte((v>>7)&0x7f|0x80),byte((v>>14)&0x7f|0x80),byte(v>>21))case v <1<<35:
b =append(b,byte((v>>0)&0x7f|0x80),byte((v>>7)&0x7f|0x80),byte((v>>14)&0x7f|0x80),byte((v>>21)&0x7f|0x80),byte(v>>28))case v <1<<42:
b =append(b,byte((v>>0)&0x7f|0x80),byte((v>>7)&0x7f|0x80),byte((v>>14)&0x7f|0x80),byte((v>>21)&0x7f|0x80),byte((v>>28)&0x7f|0x80),byte(v>>35))case v <1<<49:
b =append(b,byte((v>>0)&0x7f|0x80),byte((v>>7)&0x7f|0x80),byte((v>>14)&0x7f|0x80),byte((v>>21)&0x7f|0x80),byte((v>>28)&0x7f|0x80),byte((v>>35)&0x7f|0x80),byte(v>>42))case v <1<<56:
b =append(b,byte((v>>0)&0x7f|0x80),byte((v>>7)&0x7f|0x80),byte((v>>14)&0x7f|0x80),byte((v>>21)&0x7f|0x80),byte((v>>28)&0x7f|0x80),byte((v>>35)&0x7f|0x80),byte((v>>42)&0x7f|0x80),byte(v>>49))case v <1<<63:
b =append(b,byte((v>>0)&0x7f|0x80),byte((v>>7)&0x7f|0x80),byte((v>>14)&0x7f|0x80),byte((v>>21)&0x7f|0x80),byte((v>>28)&0x7f|0x80),byte((v>>35)&0x7f|0x80),byte((v>>42)&0x7f|0x80),byte((v>>49)&0x7f|0x80),byte(v>>56))default:
b =append(b,byte((v>>0)&0x7f|0x80),byte((v>>7)&0x7f|0x80),byte((v>>14)&0x7f|0x80),byte((v>>21)&0x7f|0x80),byte((v>>28)&0x7f|0x80),byte((v>>35)&0x7f|0x80),byte((v>>42)&0x7f|0x80),byte((v>>49)&0x7f|0x80),byte((v>>56)&0x7f|0x80),1)}return b, s
}