Go——两个[]byte数组合并成一个[]byte

方式一

使用 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.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("%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 []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("%s\n", res3)
}

测试输出

[0 16 32 48]
[0 10 20 30]
[111 110 101 116 119 111]
onetwo
♥ 喜 欢 请 点 赞 哟 ♥
(●ˇ∀ˇ●)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九思梦鹿

喜欢,请记得点赞或赞赏哟

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值