需求:分别封装方法将[]byte转换成[]unint16,将[]unint16转换成 []byte
byte相当于unint8
分析:长度为20的[]byte转换为长度为10的[]unint16,
他们之间的转换如
bytes := []byte{0, 1} ===》[0*256+1]=1 注意:第奇数乘256加偶数的值 则 []uint16的值为[1] 完整代码如下:1 package main 2 3 import ( 4 "fmt" 5 ) 6 7 func BytesToUint16s(bytes []byte) []uint16 { 8 numUint16s := len(bytes) / 2 9 uint16s := make([]uint16, numUint16s) 10 11 for i := 0; i < numUint16s; i++ { 12 uint16s[i] = uint16(bytes[i*2])<<8 | uint16(bytes[i*2+1]) 13 } 14 return uint16s 15 } 16 17 func Uint16sToBytes(uint16s []uint16) []byte { 18 numBytes := len(uint16s) * 2 19 bytes := make([]byte, numBytes) 20 21 for i := 0; i < len(uint16s); i++ { 22 bytes[i*2] = byte(uint16s[i] >> 8) 23 bytes[i*2+1] = byte(uint16s[i]) 24 } 25 return bytes 26 } 27 28 func main() { 29 bytes := []byte{0, 1, 1, 0, 19, 18, 255, 0, 0, 1, 1, 0, 19, 18, 255, 0, 19, 18, 255, 255} 30 uint16s := []uint16{1, 256, 4882, 65280, 1, 256, 4882, 65280, 4882, 65535} 31 32 getUint16s := BytesToUint16s(bytes) 33 getBytes := Uint16sToBytes(uint16s) 34 35 fmt.Println(getUint16s) 36 fmt.Println(getBytes) 37 }
标签:转换,uint16s,bytes,uint16,unint16,Go,byte,256 From: https://www.cnblogs.com/sinberya/p/17623646.html