- 方式一
- 使用 join 函数
- 测试
- 方式二
- 使用 bytes.Buffer
- 测试
- 方式三
- 使用 append ...
- 测试输出
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("%dn", BytesCombine1([]byte{1,2,3}, []byte{4,5,6}))
fmt.Printf("%sn", 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.Buffer
for 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("%dn", BytesCombine1([]byte{1, 2, 3}, []byte{4, 5, 6}))
fmt.Printf("%sn", 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 []byte
var res2 []byte
one := make([]byte, 2)
two := make([]byte, 2)
//16进制
one[0] = 0x00
one[1] = 0x010
two[0] = 0x020
two[1] = 0x030
res1 = 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("%sn", res3)
}
测试输出
[0 16 32 48] [0 10 20 30] [111 110 101 116 119 111] onetwo
| ♥ 喜 欢 请 点 赞 哟 ♥ |
| (●ˇ∀ˇ●) |


![Go——两个[]byte数组合并成一个[]byte Go——两个[]byte数组合并成一个[]byte](http://www.mshxw.com/aiimages/31/945723.png)
