数组合并成一个[]byte"/>
Go——两个[]byte数组合并成一个[]byte
合并 []byte 数组
- 方式一
- 使用 join 函数
- 测试
- 方式二
- 使用 bytes.Buffer
- 测试
- 方式三
- 使用 append ...
- 测试输出
方式一
使用 join 函数
func BytesCombine1(pBytes ...[]byte) []byte {length := len(pBytes)s := make([][]byte, length)for index := 0; index < length; index++ {s[index] = pBytes[index]}sep := []byte("")return bytes.Join(s, sep)
}
或者简化为:
func BytesCombine2(pBytes ...[]byte) []byte {return bytes.Join(pBytes, []byte("-"))
}
测试
func main() {fmt.Println(BytesCombine1([]byte{1,2,3}, []byte{4,5,6}))fmt.Println(BytesCombine1([]byte("one"), []byte("two")))fmt.Printf("%d\n", BytesCombine1([]byte{1,2,3}, []byte{4,5,6}))fmt.Printf("%s\n", BytesCombine1([]byte("one"), []byte("two")))
}
输出如下:
[1 2 3 4 5 6]
[111 110 101 116 119 111]
[1 2 3 4 5 6]
onetwo
方式二
使用 bytes.Buffer
func BytesCombine3(pBytes ...[]byte) []byte {var buffer bytes.Bufferfor index := 0; index < len(pBytes); index++ {buffer.Write(pBytes[index])}return buffer.Bytes()
}
测试
func main() {fmt.Println(BytesCombine3([]byte{1, 2, 3}, []byte{4, 5, 6}))fmt.Println(BytesCombine3([]byte("one"), []byte("two")))fmt.Printf("%d\n", BytesCombine1([]byte{1, 2, 3}, []byte{4, 5, 6}))fmt.Printf("%s\n", BytesCombine3([]byte("one"), []byte("two")))
}
输出如下:
[1 2 3 4 5 6]
[111 110 101 116 119 111]
[1 2 3 4 5 6]
onetwo
方式三
使用 append …
func BytesCombine4() {var res1 []bytevar res2 []byteone := make([]byte, 2)two := make([]byte, 2)//16进制one[0] = 0x00one[1] = 0x010two[0] = 0x020two[1] = 0x030res1 = append(one[:], two[:]...)fmt.Println(res1)//10进制three := []byte{0, 10}four := []byte{20, 30}res2 = append(three, four...)fmt.Println(res2)five := []byte("one")six := []byte("two")res3 := append(five, six...)fmt.Println(res3)fmt.Printf("%s\n", res3)
}
测试输出
[0 16 32 48]
[0 10 20 30]
[111 110 101 116 119 111]
onetwo
♥ 喜 欢 请 点 赞 哟 ♥ |
(●ˇ∀ˇ●) |
更多推荐
Go——两个[]byte数组合并成一个[]byte
发布评论